
import os

def every_file_in_dir(dir):
    result = []

    for root, dirs, files in os.walk(dir):
        for file in files:
            result.append(os.path.join(root, file))

    return result


def builtin_files_to_c(localDir, hostedPrefix):
    out = []

    out.append("// This file was autogenerated")
    out.append("")
    out.append("#include <cstring>")
    out.append("")
    out.append("namespace circa {")
    out.append("")
    out.append("const char* find_builtin_file(const char* filename) {")
    out.append("")

    out.append("    if (strncmp(filename, \""+hostedPrefix+"\", "+str(len(hostedPrefix))+") != 0)")
    out.append("        return NULL;")
    out.append("")

    def escape_line(line):
        out = []
        for c in line:
            if c == '"': out.append('\\"')
            elif c == '\\': out.append('\\\\')
            else: out.append(c)
        return "".join(out)


    for filename in every_file_in_dir(localDir):
        source = open(filename)
        localFilename = os.path.relpath(filename, localDir)

        prefixedName = hostedPrefix+localFilename

        out.append('    if (strncmp(filename, "'+prefixedName+'", '+str(len(prefixedName))+') == 0) return')

        while source:
            line = source.readline()
            if line == "": break
            line = line[:-1]
            line = escape_line(line)
            out.append('        "' + line + '\\n"')

        out.append("        ;")
        out.append("")

    out.append("")
    out.append("    return NULL;")
    out.append("}")
    out.append('')
    out.append("} // namespace circa")
    out.append("")

    return "\n".join(out)
