#!/usr/bin/env python

Import('env')
env.editor_sources = []

import os
import os.path
from compat import encode_utf8, byte_to_str, open_utf8, escape_string

def make_certs_header(target, source, env):

    src = source[0].srcnode().abspath
    dst = target[0].srcnode().abspath
    f = open(src, "rb")
    g = open_utf8(dst, "w")
    buf = f.read()
    decomp_size = len(buf)
    import zlib
    buf = zlib.compress(buf)

    g.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n")
    g.write("#ifndef _CERTS_RAW_H\n")
    g.write("#define _CERTS_RAW_H\n")
    g.write("static const int _certs_compressed_size = " + str(len(buf)) + ";\n")
    g.write("static const int _certs_uncompressed_size = " + str(decomp_size) + ";\n")
    g.write("static const unsigned char _certs_compressed[] = {\n")
    for i in range(len(buf)):
        g.write("\t" + byte_to_str(buf[i]) + ",\n")
    g.write("};\n")
    g.write("#endif")

    g.close()
    f.close()


def make_doc_header(target, source, env):

    dst = target[0].srcnode().abspath
    g = open_utf8(dst, "w")
    buf = ""
    docbegin = ""
    docend = ""
    for s in source:
        src = s.srcnode().abspath
        if not src.endswith(".xml"):
            continue
        with open_utf8(src, "r") as f:
            content = f.read()
        buf += content

    buf = encode_utf8(docbegin + buf + docend)
    decomp_size = len(buf)
    import zlib
    buf = zlib.compress(buf)

    g.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n")
    g.write("#ifndef _DOC_DATA_RAW_H\n")
    g.write("#define _DOC_DATA_RAW_H\n")
    g.write("static const int _doc_data_compressed_size = " + str(len(buf)) + ";\n")
    g.write("static const int _doc_data_uncompressed_size = " + str(decomp_size) + ";\n")
    g.write("static const unsigned char _doc_data_compressed[] = {\n")
    for i in range(len(buf)):
        g.write("\t" + byte_to_str(buf[i]) + ",\n")
    g.write("};\n")

    g.write("#endif")

    g.close()


def make_fonts_header(target, source, env):

    dst = target[0].srcnode().abspath

    g = open_utf8(dst, "w")

    g.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n")
    g.write("#ifndef _EDITOR_FONTS_H\n")
    g.write("#define _EDITOR_FONTS_H\n")

    # saving uncompressed, since freetype will reference from memory pointer
    xl_names = []
    for i in range(len(source)):
        with open(source[i].srcnode().abspath, "rb")as f:
            buf = f.read()

        name = os.path.splitext(os.path.basename(source[i].srcnode().abspath))[0]

        g.write("static const int _font_" + name + "_size = " + str(len(buf)) + ";\n")
        g.write("static const unsigned char _font_" + name + "[] = {\n")
        for i in range(len(buf)):
            g.write("\t" + byte_to_str(buf[i]) + ",\n")

        g.write("};\n")

    g.write("#endif")

    g.close()


def make_translations_header(target, source, env):

    dst = target[0].srcnode().abspath

    g = open_utf8(dst, "w")

    g.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n")
    g.write("#ifndef _EDITOR_TRANSLATIONS_H\n")
    g.write("#define _EDITOR_TRANSLATIONS_H\n")

    import zlib
    import os.path

    paths = [node.srcnode().abspath for node in source]
    sorted_paths = sorted(paths, key=lambda path: os.path.splitext(os.path.basename(path))[0])

    xl_names = []
    for i in range(len(sorted_paths)):
        with open(sorted_paths[i], "rb") as f:
            buf = f.read()
        decomp_size = len(buf)
        buf = zlib.compress(buf)
        name = os.path.splitext(os.path.basename(sorted_paths[i]))[0]

        g.write("static const unsigned char _translation_" + name + "_compressed[] = {\n")
        for i in range(len(buf)):
            g.write("\t" + byte_to_str(buf[i]) + ",\n")

        g.write("};\n")

        xl_names.append([name, len(buf), str(decomp_size)])

    g.write("struct EditorTranslationList {\n")
    g.write("\tconst char* lang;\n")
    g.write("\tint comp_size;\n")
    g.write("\tint uncomp_size;\n")
    g.write("\tconst unsigned char* data;\n")
    g.write("};\n\n")
    g.write("static EditorTranslationList _editor_translations[] = {\n")
    for x in xl_names:
        g.write("\t{ \"" + x[0] + "\", " + str(x[1]) + ", " + str(x[2]) + ", _translation_" + x[0] + "_compressed},\n")
    g.write("\t{NULL, 0, 0, NULL}\n")
    g.write("};\n")

    g.write("#endif")

    g.close()

def _make_doc_data_class_path(to_path):
    g = open_utf8(os.path.join(to_path,"doc_data_class_path.gen.h"), "w")
    g.write("static const int _doc_data_class_path_count = " + str(len(env.doc_class_path)) + ";\n")
    g.write("struct _DocDataClassPath { const char* name; const char* path; };\n")

    g.write("static const _DocDataClassPath _doc_data_class_paths[" + str(len(env.doc_class_path) + 1) + "] = {\n");
    for c in sorted(env.doc_class_path):
        g.write("\t{\"" + c + "\", \"" + env.doc_class_path[c] + "\"},\n")
    g.write("\t{NULL, NULL}\n")
    g.write("};\n")

    g.close()


if env['tools']:
    # Register exporters
    reg_exporters_inc = '#include "register_exporters.h"\n'
    reg_exporters = 'void register_exporters() {\n'
    for e in env.platform_exporters:
        env.editor_sources.append("#platform/" + e + "/export/export.cpp")
        reg_exporters += '\tregister_' + e + '_exporter();\n'
        reg_exporters_inc += '#include "platform/' + e + '/export/export.h"\n'
    reg_exporters += '}\n'
    with open_utf8("register_exporters.gen.cpp", "w") as f:
        f.write(reg_exporters_inc)
        f.write(reg_exporters)

    # API documentation
    docs = []
    doc_dirs = ["doc/classes"]

    for p in env.doc_class_path.values():
        if p not in doc_dirs:
            doc_dirs.append(p)

    for d in doc_dirs:
        try:
            for f in os.listdir(os.path.join(env.Dir('#').abspath, d)):
                docs.append("#" + os.path.join(d, f))
        except OSError:
            pass

    _make_doc_data_class_path(os.path.join(env.Dir('#').abspath, "editor/doc"))

    docs = sorted(docs)
    env.Depends("#editor/doc_data_compressed.gen.h", docs)
    env.CommandNoCache("#editor/doc_data_compressed.gen.h", docs, make_doc_header)
    # Certificates
    env.Depends("#editor/certs_compressed.gen.h", "#thirdparty/certs/ca-certificates.crt")
    env.CommandNoCache("#editor/certs_compressed.gen.h", "#thirdparty/certs/ca-certificates.crt", make_certs_header)

    import glob
    path = env.Dir('.').abspath

    # Translations
    tlist = glob.glob(path + "/translations/*.po")
    env.Depends('#editor/translations.gen.h', tlist)
    env.CommandNoCache('#editor/translations.gen.h', tlist, make_translations_header)

    # Fonts
    flist = glob.glob(path + "/../thirdparty/fonts/*.ttf")
    flist.append(glob.glob(path + "/../thirdparty/fonts/*.otf"))
    env.Depends('#editor/builtin_fonts.gen.h', flist)
    env.CommandNoCache('#editor/builtin_fonts.gen.h', flist, make_fonts_header)

    env.add_source_files(env.editor_sources, "*.cpp")
    env.add_source_files(env.editor_sources, ["#thirdparty/misc/clipper.cpp"])

    SConscript('collada/SCsub')
    SConscript('doc/SCsub')
    SConscript('fileserver/SCsub')
    SConscript('icons/SCsub')
    SConscript('import/SCsub')
    SConscript('plugins/SCsub')

    lib = env.add_library("editor", env.editor_sources)
    env.Prepend(LIBS=[lib])

    Export('env')