import FairyGUI = CS.FairyGUI;
import FairyEditor = CS.FairyEditor;
import System = CS.System;
const App = FairyEditor.App;
const File = System.IO.File;
const Directory = System.IO.Directory;

export class LanguageComponentChildData {
    id: string;
    key: string;
    useable: number;
}

// class LanguageComponentData {
//     url: string;
//     childs: object = {};
// }

export class LanguagePackageData {
    name: string;
    components: object = {};
}

export class LanguageSettings {
    private static instance: LanguageSettings;
    static getInstance() {
        if (!this.instance) {
            this.instance = new LanguageSettings();
        }
        return this.instance;
    }


    public componentsSettingBasePath: string = "";
    private readonly _languageMap: Map<string, LanguagePackageData> = new Map<string, LanguagePackageData>();
    private readonly _languageKeyValues: object = {};

    constructor() {
        this.init()
        // this._languageKeyValues['k1'] = "hahha1"
        // this._languageKeyValues['k2'] = "hahha2"
        // this._languageKeyValues['k3'] = "hahha3"
        //'CustomProperties'
        let path = App.project.settingsPath + "/CustomProperties.json"
        if (File.Exists(path)) {
            let jsonStr = File.ReadAllText(path);
            let settings = JSON.parse(jsonStr) as object
            if (settings.hasOwnProperty("languagePath")) {
                let languagePath = App.project.basePath + "/" + settings['languagePath']
                console.log("多语言路径=", languagePath)
                if (File.Exists(languagePath)) {
                    let languageStr = File.ReadAllText(languagePath);
                    let datas = JSON.parse(languageStr) as Array<object>
                    if (datas != null && datas.length > 0) {
                        for (const data of datas) {
                            this._languageKeyValues[data['key']] = data['value']
                        }
                    }
                }

            }

        }
    }

    private init() {
        console.log("初始化加载多语言配置===")

        this.componentsSettingBasePath = App.project.settingsPath + "/whootLanguage"
        if (!System.IO.Directory.Exists(this.componentsSettingBasePath)) {
            console.log("whoot配置文件目录不存在，创建")
            System.IO.Directory.CreateDirectory(this.componentsSettingBasePath)
        }
        this.readAll()
    }

    /**
     * 清理无效的配置
     */
    clearFailureConfig() {
        // App.d
    }

    getLanguage(key: string): string {
        let value = this._languageKeyValues[key]
        if (value == null) {
            return key
        }
        return value;
    }

    /**
     * 获取所有多语言包配置
     * @returns 
     */
    getAllPackage(): Map<string, LanguagePackageData> {
        return this._languageMap;
    }

    /**
     * 获取一个多语言配置
     * @param packageName 
     * @param docUrl 
     * @param componentId 
     */
    get(packageName, docUrl, componentId): LanguageComponentChildData {
        let pack = this._languageMap.get(packageName)
        if (pack != null) {
            let doc = pack.components[docUrl]
            if (doc != null) {
                let child = doc[componentId]
                return child as LanguageComponentChildData
            }
        }
        return null;
    }

    /**
     * 获取一个组件的多语言配置
     * @param packageName 
     * @param docUrl 
     * @returns 
     */
    getDoc(packageName, docUrl): object {
        let pack = this._languageMap.get(packageName)
        if (pack != null) {
            let doc = pack.components[docUrl]
            if (doc != null) {
                return doc as object
            }
        }
        return null;
    }

    /**
     * 获取一个包的多语言配置
     * @param packageName 
     */
    getPackage(packageName): object {
        let pack = this._languageMap.get(packageName)
        if (pack) {
            return pack.components;
        }
        return {};
    }


    /**
     * 更新一个多语言配置
     * @param packageName 
     * @param docUrl 
     * @param componentId 
     * @param languageKey 
     * @param useable 是否可用的 
     */
    update(packageName, docUrl, componentId, languageKey, useable: boolean = true): boolean {
        let chang = false
        let pack = this._languageMap.get(packageName)
        if (pack == null) {
            pack = new LanguagePackageData()
            pack.name = packageName
            this._languageMap.set(packageName, pack)
            chang = true
        }
        let doc = pack.components[docUrl]
        if (doc == null) {
            doc = {};
            pack.components[docUrl] = doc;//.set(docUrl, doc)
            chang = true
        }
        let child = doc[componentId]
        if (child == null) {
            child = new LanguageComponentChildData();
            child.id = componentId
            doc[componentId] = child//.set(componentId, child)
        }
        let u = useable ? 1 : 0
        if (child.key != languageKey || child.useable != u) {
            child.key = languageKey
            child.useable = u
            chang = true
        }

        if (chang) {
            //有数据变化，变更文件
            this.saveFile(packageName)
        }
        return chang
    }


    //region 工具方法
    updateItemTitle(obj: FairyEditor.FObject, key: string) {
        // console.log("obj类型=", obj.GetType())
        if (obj instanceof FairyEditor.FTextInput) {
            let textInput = obj as FairyEditor.FTextInput
            textInput.promptText = this.getLanguage(key)
        } else if (obj instanceof FairyEditor.FButton) {
            let button = obj as FairyEditor.FButton
            button.title = this.getLanguage(key)
        } else if (obj instanceof FairyEditor.FLabel) {
            let lable = obj as FairyEditor.FLabel
            lable.title = this.getLanguage(key)
        } else {
            obj.text = this.getLanguage(key)
        }
    }
    //endregion


    //region file
    //获取所有的文件的路径
    private getAllDirector(path: string, list: Array<string>) {
        console.log("开始读取所有配置=", path)
        let files = Directory.GetFiles(path, "*.json")
        for (let f = 0; f < files.Length; f++) {
            list.push(files.get_Item(f))
        }

    }
    /**
     * 读取全部
     */
    private readAll() {
        try {
            let list: Array<string> = []
            this.getAllDirector(this.componentsSettingBasePath, list)
            this._languageMap.clear()
            console.log("初始化所有多语言配置")
            for (let index = 0; index < list.length; index++) {
                let p = list[index];
                let jsonStr = File.ReadAllText(p);
                let data: LanguagePackageData = JSON.parse(jsonStr);
                this._languageMap.set(data.name, data)
            }
        } catch {
            console.error("读取多语言配置文件失败")
        }
    }

    /**
     * 将所有配置保存成配置文件
     */
    private saveAllFile() {
        let keys = this._languageMap.keys()
        for (const key of keys) {
            this.saveFile(key)
        }
    }
    /**
     * 保存json文件
     * @param packageName 
     */
    private saveFile(packageName: string) {
        let path = this.componentsSettingBasePath + "/" + packageName + ".json";
        let data = this._languageMap.get(packageName)
        if (data != null) {
            let jsonStr = JSON.stringify(data);
            File.WriteAllText(path, jsonStr)
        }

    }
    //endregion
}

export default LanguageSettings.getInstance();