import os
import json
import platform
from pathlib import Path

project = {
    "name": "evue-awtk", # xxx.pro,
    "modules": {
        "crane_lvgl_W31/external/zlib": "",
        "crane_lvgl_W31/external/libpng": "",
        "crane_lvgl_W31/external/libjpeg-turbo": "",
        "crane_lvgl_W31/external/libqrencode": "",
        "crane_lvgl_W31/gui/lv_watch": "",
        "crane_lvgl_W31/gui/lv_drivers": "",
        "ecma/src": "ecma"
    }
}

def get_module_name(path):
    for key in project.get("modules"):
        if Path(path).as_posix().find(key) >= 0:
            result = key.split("/")[-1]
            if len(project.get("modules").get(key)) > 0:
                result = project.get("modules").get(key)
            return result
    return Path(path).as_posix().split("/")[-1]

def gen_pro_from_build_log(projectname, root_dir, filename, output_dir):
    source_path = Path(filename)
    target_path = Path(output_dir)

    with open(source_path.as_posix(), "r", encoding="utf-8") as f:
        lines = f.readlines()

    gccLines = [l for l in lines if l.find("-o") >= 0]

    pris = {}
    defs = "" # define
    incs = "" # include
    lnks = "" # link

    pri_files = []
    srcs = "SOURCES += \\\n"
    ss = "$$PWD/../" # 相对路径的问题
    tmp = ""
    pro_relative_path = "$$PWD/"
    parent_path = Path(output_dir)
    while Path(root_dir).absolute().as_posix() != parent_path.absolute().as_posix():
        tmp += "../"
        pro_relative_path += "../"
        parent_path = parent_path.parent
    # print("tmp ========>", tmp)
    ss += tmp

    for l in gccLines:
        options = l.split(' ')
        name = options[-1].split("\\")[-1]
        path = options[-1][:-len(name)]

        defines = []
        includes = []
        links = []
        for d in options:
            if d.startswith("-D"):
                defines.append(d[2:])

            if d.startswith("-I"):
                includes.append(d[2:])

            if d.startswith("-l") or d.startswith("-L"):
                links.append(d)
        
        if path not in pris:
            pris[path] = []

        pris[path].append({
            'name': name,
            'fullpath': Path(options[-1].replace("\n", "")).as_posix()
        })

        if defs == "":
            for d in defines:
                defs += "DEFINES += " + d + " \n"

        if incs == "":
            for i in includes:
                incs += "INCLUDEPATH += " + pro_relative_path + i + "\n"

        if lnks == "":
            for i in links:
                lnks += "LIBS += " + i + "\n"

    with open("a.json", "w+") as f:
        f.write(json.dumps(pris))

    for key in pris:
        if len(key) <= 0:
            continue

        for d in pris[key]:
            fn = get_module_name(key) + ".pri"
            print(d["fullpath"], " <=====> ", fn)

            if fn not in pri_files:
                pri_files.append(fn)

            if not target_path.joinpath("pris").exists():
                os.makedirs(target_path.joinpath("pris").absolute().as_posix())

            if not target_path.joinpath("pris").joinpath(fn).exists():
                with open(target_path.joinpath("pris").joinpath(fn).absolute().as_posix(), "w+") as f:
                    f.write(srcs + " " * (len(srcs) - 4) + ss +  d["fullpath"] + " \\\n")
            else:
                with open(target_path.joinpath("pris").joinpath(fn).absolute().as_posix(), "a+") as f:
                    f.write(" " * (len(srcs) - 4) + ss + d["fullpath"] + " \\\n")

    target_name = projectname.split("\\")[-1].replace(".log", "").replace(".exe", "")
    pro_file = target_path.joinpath("{}.pro".format(target_name)).absolute().as_posix()
    with open(pro_file, "w+") as f:
        f.write('''
TEMPLATE = app
TARGET = {}
CONFIG -= app_bundle
CONFIG -= qt\n
    '''.format(target_name))
        f.write("\n{}\n\n{}\n\n{}\n\n".format(lnks, defs, incs))
        for aa in pri_files:
            f.write("include(pris/{})".format(aa) + "\n")

    return pro_file

if __name__ == "__main__":
    # root_dir = "./"
    # output_dir = "build_log"
    # tmp = "$$PWD/"
    # parent_path = Path(output_dir)

    # while Path(root_dir).absolute().as_posix() != parent_path.absolute().as_posix():
    #     tmp += "../"
    #     parent_path = parent_path.parent
    #     print(parent_path.absolute().as_posix())

    # print("tmp ========>", tmp)
    gen_pro_from_build_log("evue-awtk", ".", "./build.log", "project")