"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.genCodeTs = genCodeTs;
const csharp_1 = require("csharp");
const CodeWriter_1 = require("./CodeWriter");
class GenClassInfo {
    name;
    varName;
    type;
    customType;
    otherPkgName;
    constructor(member) {
        this.name = member.name;
        this.varName = member.varName;
        this.type = member.type;
        this.customType = false;
    }
}
let exportLangKV = new Map();
/**UI的vm类名后缀*/
let vmSuffix = "VM";
function genCodeTs(handler) {
    let settings = handler.project.GetSettings("Publish").codeGeneration;
    let codePkgName = handler.ToFilename(handler.pkg.name); //convert chinese to pinyin, remove special chars etc.
    codePkgName = myCapitalize(codePkgName);
    //package代码的根目录
    let exportCodePath = `${handler.exportCodePath}/${codePkgName}`;
    //模板代码根目录
    let codeTemplatesPath = handler.project.assetsPath.replace("assets", "plugins/xgame_gen_code/Templates/ts");
    console.log(`CodePath:${exportCodePath} codePkgName:${codePkgName}`);
    console.log(`codeTemplatesPath:${codeTemplatesPath} getMemberByName:${settings.getMemberByName}`);
    //CollectClasses(stripeMemeber, stripeClass, fguiNamespace)
    let classes = handler.CollectClasses(settings.ignoreNoname, settings.ignoreNoname, null);
    // handler.SetupCodeFolder(exportCodePath, "cs"); //check if target folder exists, and delete old files
    //创建Package代码文件夹
    if (!csharp_1.System.IO.Directory.Exists(exportCodePath)) {
        csharp_1.System.IO.Directory.CreateDirectory(exportCodePath);
    }
    let classCnt = classes.Count;
    let writer = new CodeWriter_1.default();
    // 一个个导出类导出
    for (let i = 0; i < classCnt; i++) {
        let classInfo = classes.get_Item(i);
        if (!checkPackageItemIsGenCode(handler, classInfo.res)) {
            // console.warn("不需要导出:" + classInfo.resName)
            continue;
        }
        else {
            console.log("导出:" + classInfo.resName);
        }
        logClassInfo(classInfo);
        let resName = myCapitalize(classInfo.resName);
        let uiName = resName;
        let uiCodePath = `${exportCodePath}/${resName}`;
        //创建UI窗口的代码文件夹
        if (!csharp_1.System.IO.Directory.Exists(uiCodePath)) {
            csharp_1.System.IO.Directory.CreateDirectory(uiCodePath);
        }
        if (classInfo.res.exported) {
            // 有设置导出属性的才生成View和Ctrl代码
            genUIClassOnce(uiCodePath, codeTemplatesPath, codePkgName, resName, uiName, "View");
        }
        // genUIClassOnce(uiCodePath, codeTemplatesPath, codePkgName, resName, uiName, vmSuffix);
        // 需要绑定的组件变量
        let genClassTypeMap = new Map();
        // 需要多语言转义的变量
        let langTypeMap = new Map();
        // TODO 该信息后续看是否需要生成脚本
        let otherPkgName = new Array();
        // 提前先获取一次生成组件变量存在引用的生成代码或者跨包的生成代码类.
        for (let index = 0; index < classInfo.members?.Count; index++) {
            const element = classInfo.members.get_Item(index);
            console.log("element.name:" + element.name + " varName:" + element.varName + " type:" + element.type);
            if (element.res) {
                let desc = handler.GetItemDesc(element.res);
                let superClassName = desc?.GetAttribute("extention");
                //fgui的组件.xml文件，如果是普通组件，则没有extention属性，否则extention会记录具体的组件类型
                // 是一个自定义组件
                console.log("element.res name:" + element.res.name + " owner.name:" + element.res.owner.name + " type:" + element.res.type
                    + " super:" + superClassName);
                // 如果是当前的包那么直接发布
                // 如果是其他包。那么需要判断这个是否需要生成代码的，否则也是直接当成是component组件引用
                if (element.res.owner.name == handler.pkg.name) {
                    // 判断是否需要导出生成代码类否则直接生成扩展类吧
                    if (checkPackageItemIsGenCode(handler, element.res)) { //&& element.res.exported
                        let className = `${codePkgName}${myCapitalize(element.res.name)}${vmSuffix}`;
                        if (otherPkgName.indexOf(className) == -1) {
                            otherPkgName.push(className);
                        }
                    }
                    else {
                        // 生成绑定ext类
                    }
                }
                else {
                    // 不在同一个包，需要读取目标路径的配置xml判断是否需要生成
                    if (checkOtherPackageItemIsGenCode(element.res)) {
                        // console.log("引用其他包的资源可以生成代码:" + element.res.owner.name + "." + element.res.name)
                        let className = `${myCapitalize(element.res.owner.name)}${myCapitalize(element.res.name)}${vmSuffix}`;
                        if (otherPkgName.indexOf(className) == -1) {
                            otherPkgName.push(className);
                            // writer.writeln('import { %s } from "../%s/%s";', className + "_" + element.res.owner.name, element.res.owner.name, className + "_" + element.res.owner.name)
                        }
                    }
                }
            }
        }
        // 组件变量
        for (let index = 0; index < classInfo.members?.Count; index++) {
            const element = classInfo.members.get_Item(index);
            if (element.res) {
                // 如果是当前的包那么直接发布
                // 如果是其他包。那么需要判断这个是否需要生成代码的，否则也是直接当成是component组件引用
                if (element.res.owner.name == handler.pkg.name) {
                    // 判断是否需要导出生成代码类否则直接生成扩展类吧
                    // 只有当这个组件资源里面勾选了生成代码 + exported才生成代码
                    if (checkPackageItemIsGenCode(handler, element.res)) { // && element.res.exported
                        // 有生成代码标记
                        let gci = new GenClassInfo(element);
                        gci.type = `${myCapitalize(element.res.name)}${vmSuffix}`;
                        gci.customType = true;
                        genClassTypeMap.set(element.varName, gci);
                    }
                    // 通过判断在该组件是否勾选了导出，那么也需要生成一下ext类
                    else {
                        let desc = handler.GetItemDesc(element.res);
                        let superClassName = desc?.GetAttribute("extention");
                        console.log(`GetItemDesc name:${element.res.name} exported:${element.res.exported} ext:${superClassName}`);
                        if (!superClassName) {
                            // // null = GComponent
                            // writer.writeln('public FairyGUI.GComponent %s;', element.varName)
                            let gci = new GenClassInfo(element);
                            gci.type = "GComponent";
                            genClassTypeMap.set(element.varName, gci);
                            // 如果有title的可以?
                            if (checkPackageItemIsLang(handler, classInfo.res, element.name)) {
                                gci = new GenClassInfo(element);
                                gci.type = superClassName;
                                langTypeMap.set(element.varName, gci);
                            }
                        }
                        else {
                            // writer.writeln('public FairyGUI.G%s %s;',superClassName, element.varName)
                            let gci = new GenClassInfo(element);
                            gci.type = "G" + superClassName;
                            genClassTypeMap.set(element.varName, gci);
                            if (checkPackageItemIsLang(handler, classInfo.res, element.name)) {
                                langTypeMap.set(element.varName, gci);
                            }
                        }
                    }
                }
                else {
                    // 不在同一个包，需要读取目标路径的配置xml判断是否需要生成
                    if (checkOtherPackageItemIsGenCode(element.res)) {
                        // // console.log("引用其他包的资源可以生成代码:" + element.res.owner.name + "." + element.res.name)
                        let gci = new GenClassInfo(element);
                        gci.type = `${myCapitalize(element.res.name)}${vmSuffix}`;
                        gci.customType = true;
                        gci.otherPkgName = myCapitalize(element.res.owner.name);
                        genClassTypeMap.set(element.varName, gci);
                    }
                    else {
                        let superClassName = checkOtherPackageItemExtension(element.res);
                        if (superClassName) {
                            // writer.writeln('public FairyGUI.G%s %s;',superClassName, element.varName)
                            let gci = new GenClassInfo(element);
                            gci.type = "G" + superClassName;
                            genClassTypeMap.set(element.varName, gci);
                            if (checkPackageItemIsLang(handler, classInfo.res, element.name)) {
                                langTypeMap.set(element.varName, gci);
                            }
                        }
                        else {
                            let gci = new GenClassInfo(element);
                            gci.type = "GComponent";
                            genClassTypeMap.set(element.varName, gci);
                            if (checkPackageItemIsLang(handler, classInfo.res, element.name)) {
                                langTypeMap.set(element.varName, gci);
                            }
                        }
                    }
                }
            }
            else {
                // fgui 默认的组件变量即可
                // writer.writeln('public FairyGUI.%s %s;',element.type, element.varName)
                genClassTypeMap.set(element.varName, new GenClassInfo(element));
                if (checkPackageItemIsLang(handler, classInfo.res, element.name)) {
                    langTypeMap.set(element.varName, new GenClassInfo(element));
                }
            }
        }
        if (classInfo.res.exported) {
            // 有设置导出属性的才生成Ctrl代码
            genUIClassOnce(uiCodePath, codeTemplatesPath, codePkgName, resName, uiName, "Ctrl", genClassTypeMap);
        }
        genViewModelClass(uiCodePath, codeTemplatesPath, codePkgName, resName, uiName, genClassTypeMap);
    }
    // 写一个binder类可以直接获取这个package导出的信息
    // 如果有些组件需要绑定的也可以绑定这个组件类型
    // let binderName = "GenMain_" + codePkgName;
    // writer.writeln('export class %s', binderName)
    // writer.startBlock()
    // writer.writeln()
    // writer.writeln('public static PackageName:string = "%s";', handler.pkg.name)
    // writer.writeln()
    // // 把这个包导出的类记录一下引用的类名
    // // bindall扩展类绑定
    // writer.writeln('public static bindAll()');
    // writer.startBlock();
    // // for (let i: number = 0; i < classCnt; i++) {
    // //     let classInfo = classes.get_Item(i);
    // //     writer.writeln('UIObjectFactory.SetPackageItemExtension(%s.URL, typeof(%s));', classInfo.className, classInfo.className);
    // // }
    // writer.endBlock(); //bindall
    // writer.endBlock()
    // writer.save(exportCodePath + '/' + binderName + '.ts');
    writer.reset();
    // 把该包多语言的kv保存下来
    if (exportLangKV.size > 0) {
        exportLangKV.forEach((v, k) => {
            writer.writeln("%s  %s", k, v);
        });
        writer.save(exportCodePath + '/' + "lang_" + codePkgName + '.txt');
    }
    writer.reset();
}
/**
 * 创建UI代码，已经存在则跳过
 * 不重复创建
 * classSuffix 类名后缀：View、ViewCtrl、ViewModel等
*/
function genUIClassOnce(uiCodePath, codeTemplatesPath, pkgName, panelName, uiName, classSuffix, genClassTypeMap = null) {
    let uiClassName = uiName + classSuffix;
    let uiClassPath = `${uiCodePath}/${uiClassName}.ts`;
    if (csharp_1.System.IO.File.Exists(uiClassPath)) {
        console.log(`${uiClassName}已经存在，不重复创建`);
        // System.IO.File.Delete(uiClassPath);
        return;
    }
    let uiClassText = csharp_1.System.IO.File.ReadAllText(`${codeTemplatesPath}/Template${classSuffix}.ts`);
    uiClassText = uiClassText.replaceAll("<#pkgName>", pkgName);
    uiClassText = uiClassText.replaceAll("<#prefabName>", panelName);
    uiClassText = uiClassText.replaceAll("<#UIName>", uiName);
    if (genClassTypeMap != null) {
        uiClassText = genButtonEvents(uiClassText, genClassTypeMap);
    }
    csharp_1.System.IO.File.WriteAllText(uiClassPath, uiClassText);
}
/**生成GButton的onClick注册代码*/
function genButtonEvents(uiClassText, genClassTypeMap) {
    let uiEventsAdd = "";
    // let uiEventsRemove: string = "";
    let uiEventsDefine = "";
    genClassTypeMap.forEach((v, k) => {
        if (v.type == "GButton") {
            let btnName = myCapitalize(v.name);
            let functionName = `OnClick${btnName}`;
            // uiEventsAdd += `        this.VM.${btnName}.onClick(this.${functionName}, this);\n`;
            uiEventsAdd += `        this.RegisterClick(this.VM.${btnName}, this.${functionName});\n`;
            // uiEventsRemove += `        this.VM.${btnName}.offClick(this.${functionName}, this);\n`;
            uiEventsDefine += `    private ${functionName}(): void {
    }\n`;
        }
    });
    uiClassText = uiClassText.replace("<#UIEventsAddArea>", uiEventsAdd);
    // uiClassText = uiClassText.replace("<#UIEventsRemoveArea>", uiEventsRemove);
    uiClassText = uiClassText.replace("<#UIEventsDefineArea>", uiEventsDefine);
    return uiClassText;
}
/**
 * 生成ViewModel.Gen代码
 * 每次都会重新生成
*/
function genViewModelClass(uiCodePath, codeTemplatesPath, pkgName, panelName, uiName, genClassTypeMap) {
    let vmClassName = `${uiName}${vmSuffix}`;
    let vmClassPath = `${uiCodePath}/${vmClassName}.ts`;
    if (csharp_1.System.IO.File.Exists(vmClassPath)) {
        //删除旧文件
        csharp_1.System.IO.File.Delete(vmClassPath);
    }
    let vmClassText = csharp_1.System.IO.File.ReadAllText(`${codeTemplatesPath}/Template${vmSuffix}.ts`);
    vmClassText = vmClassText.replaceAll("<#pkgName>", pkgName);
    vmClassText = vmClassText.replaceAll("<#prefabName>", panelName);
    vmClassText = vmClassText.replaceAll("<#UIName>", uiName);
    // 开始绑定组件get
    let propertyDefine = "";
    let propertyAssign = "";
    let importArea = "";
    genClassTypeMap.forEach((v, k) => {
        propertyDefine += `    readonly ${myCapitalize(v.name)}: ${v.customType ? "" : "fgui."}${v.type};\n`;
        // let eTypeWithoutG = v.type.slice(1,v.type.length); // component组件名字去掉开头的'G'
        if (v.customType) {
            propertyAssign += `        this.${myCapitalize(v.name)} = new ${v.type}(panel.getChild("${v.name}") as fgui.GComponent);\n`;
            if (v.otherPkgName) {
                importArea += `import { ${v.type} } from "../../${v.otherPkgName}/${v.type.replace(vmSuffix, "")}/${v.type}";\n`;
            }
            else {
                importArea += `import { ${v.type} } from "../${v.type.replace(vmSuffix, "")}/${v.type}";\n`;
            }
            // propertyAssign += `            ${myCapitalize(v.name)} = (panel.GetChild("${v.superName}").asCom).GetChild("${v.name}").as${eTypeWithoutG};\n\r`;
        }
        else {
            if (v.type == "Controller") {
                propertyAssign += `        this.${myCapitalize(v.name)} = panel.getController("${v.name}");\n`;
            }
            else if (v.type == "Transition") {
                propertyAssign += `        this.${myCapitalize(v.name)} = panel.getTransition("${v.name}");\n`;
            }
            else {
                propertyAssign += `        this.${myCapitalize(v.name)} = panel.getChild("${v.name}") as fgui.${v.type};\n`;
            }
        }
    });
    vmClassText = vmClassText.replace("<#importArea>", importArea);
    vmClassText = vmClassText.replace("<#PropertyDefineArea>", propertyDefine);
    vmClassText = vmClassText.replace("<#PropertyAssignArea>", propertyAssign);
    csharp_1.System.IO.File.WriteAllText(vmClassPath, vmClassText);
}
function genBindClass(handler, pkgItem) {
    let writer = new CodeWriter_1.default();
    // if (!checkPackageItemIsGenCode(handler, pkgItem)) {
    //     return
    // } else {
    //     console.log("导出:" + pkgItem.name)
    // }
    writer.reset();
    writer.writeln('import { FairyGUI } from \'csharp\';');
    writer.writeln('import { binder } from \'framework/common/NiceDecorator\';');
    writer.writeln('import { BaseUI, UILayer } from "../../../framework/ui/BaseUI";');
    writer.writeln();
    pkgItem = handler.pkg.GetItem(pkgItem.id);
    console.log(pkgItem.name + " - " + pkgItem.file);
    console.log(pkgItem.GetURL());
    let pkg = pkgItem.GetTrunk();
    // 提前先获取一次生成组件变量存在引用的生成代码或者跨包的生成代码类.
    for (let index = 0; index < pkg.children.Count; index++) {
        const child = pkg.children.get_Item(index);
        console.log("child : " + child.name);
    }
}
function checkPackageItemIsLang(handler, pkgItem, refComponentName) {
    // console.log("found lang  = " + refComponentName)
    console.log(`checkPackageItemIsLang pkgItem.file:${pkgItem.file}`);
    let file = csharp_1.System.IO.File.ReadAllText(pkgItem.file);
    let xml = new csharp_1.FairyGUI.Utils.XML(file);
    let sd = xml?.GetNode("scriptData");
    if (!sd) {
        return false;
    }
    let eles = xml?.GetNode("displayList")?.Elements();
    for (let index = 0; index < eles?.Count; index++) {
        const element = eles.get_Item(index);
        if (element.GetAttribute("name") == refComponentName) {
            // 获取这个组件id
            let id = element.GetAttribute("id");
            // 然后跑去找这个配置的lang是否是1
            if (sd.GetAttribute("lang" + id) == "1") {
                let key = handler.pkg.name + "." + pkgItem.name + "." + refComponentName;
                // 保存一下这个多语言的key - text
                if (element.HasAttribute("text")) {
                    exportLangKV.set(key, element.GetAttribute("text"));
                }
                else if (element.HasAttribute("url")) {
                    exportLangKV.set(key, element.GetAttribute("url"));
                }
                else if (element.GetNode("Button")?.HasAttribute("title")) {
                    exportLangKV.set(key, element.GetNode("Button").GetAttribute("title"));
                }
                else if (element.GetNode("Label")?.HasAttribute("title")) {
                    exportLangKV.set(key, element.GetNode("Label").GetAttribute("title"));
                }
                return true;
            }
            else {
                return false;
            }
        }
    }
    return false;
}
/**
 * 判断包内Item是否有生成代码标记
*/
function checkPackageItemIsGenCode(handler, pkgItem) {
    let xml = handler.GetScriptData(pkgItem);
    let gencode = xml?.GetAttribute("gencode" + pkgItem.id);
    if (gencode == "1") {
        return true;
    }
    return false;
}
// 例如一个组件里面选择了某个丢进来的组件勾选了生成代码，但是这个组件不生成实例化代码就用ext
function checkComponentIsGenCode(handler, pkgItem, refComponentId) {
    let xml = handler.GetScriptData(pkgItem);
    let gencode = xml?.GetAttribute("gencode" + refComponentId);
    if (gencode == "1") {
        return true;
    }
    return false;
}
/**
 * 判断其他包内Item是否有生成代码标记
*/
function checkOtherPackageItemIsGenCode(pkgItem) {
    let file = csharp_1.System.IO.File.ReadAllText(pkgItem.file);
    let xml = new csharp_1.FairyGUI.Utils.XML(file);
    let gencode = xml?.GetNode("scriptData")?.GetAttribute("gencode" + pkgItem.id);
    if (gencode == "1") {
        return true;
    }
    return false;
}
//fgui的组件.xml文件，如果是普通组件，则没有extention属性，否则extention会记录具体的组件类型(去掉了开头的'G')
function checkOtherPackageItemExtension(pkgItem) {
    let file = csharp_1.System.IO.File.ReadAllText(pkgItem.file);
    let xml = new csharp_1.FairyGUI.Utils.XML(file);
    return xml?.GetAttribute("extention");
}
function logClassInfo(ci) {
    console.log(ci.superClassName + "." + ci.className + " resName=" + ci.resName + " resId=" + ci.resId);
    // for (let index = 0; index < ci.members?.Count; index++) {
    //     const element = ci.members.get_Item(index);
    //     console.log("       > " + element.name + " -v:" + element.varName + " -t:" + element.type )
    //     if(element.res) {
    //         console.log("           : res=" + element.res.name + " 包名:" + element.res.owner.name)
    //     }
    // }
    for (let index = 0; index < ci.references?.Count; index++) {
        const element = ci.references.get_Item(index);
        console.log("           >> ref:" + element);
    }
}
/**
 * 字符串首字母转大写
*/
function myCapitalize(str) {
    return str[0].toUpperCase() + str.slice(1, str.length);
}
