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 MemberData {
    public id: string
    public name: string
    /** 使用自定义脚本 **/
    public useCustomScript: boolean
    public annotation: string = "";
}

export class ComponentData {
    constructor() {
        this.member = {}
    }
    public url: string;
    public name: string;
    public scriptType: string = "";
    public isCustomName: boolean = false
    public customName: string = "";
    public annotation: string = "";
    public member = {}
}

export class GenCodeSettingData {
    constructor() {
        this.components = {}
    }
    public components = {}
}


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

    public settingPath: string = "";
    public componentsSettingBasePath: string = "";
    private settingData: GenCodeSettingData;
    constructor() {
        this.settingPath = App.project.settingsPath + "/WhootGencodeSetting.json"
        this.componentsSettingBasePath = App.project.settingsPath + "/whoot"
        if (!System.IO.Directory.Exists(this.componentsSettingBasePath)) {
            console.log("whoot配置文件目录不存在，创建")
            System.IO.Directory.CreateDirectory(this.componentsSettingBasePath)
        }
        this.readAll()
    }

    /**
     * 清理已经失效的url
     */
    public clearFailureConfig() {
        console.log("清理全部已经失效的资源")
    }

    public test() {
        console.log("hahah")
    }


    public getComponentSetting(url: string) {
        if (this.settingData.components != null && this.settingData.components.hasOwnProperty(url)) {
            return this.settingData.components[url]
        }
        return null
    }

    public changeComponentSetting(url: string, type: string, name: string, isCuston: boolean = false, customName: string = "", annotation: string = "") {
        let com: ComponentData = null

        if (!this.settingData.components.hasOwnProperty(url)) {
            com = new ComponentData()
            //新建
            this.settingData.components[url] = com;
        } else {
            com = this.settingData.components[url]
        }
        com.url = url
        com.scriptType = type
        com.isCustomName = isCuston
        com.customName = customName
        com.name = name
        com.annotation = annotation

        this.save(url)
    }

    public packageItemChange(context: FairyGUI.EventContext) {
        var item = context.data as FairyEditor.FPackageItem
        if (item != null && item.isDisposed) {
            console.log("包的文件改变了，有文件被删除", this.settingData)
            if (this.settingData != null && this.settingData.components != null) {
                let url = item.GetURL()
                console.log("删除了的url=" + url)
                this.delete(url)
                delete this.settingData.components[url]

            }
        } else if (item != null) {
            console.log("包的文件改变了。文件增加")
        }
    }

    // public getMemberSettingByName(baseUrl: string, name: string) {
    //     var baseData: ComponentData = this.getComponentSetting(baseUrl);
    //     if (baseData != null) {
    //         if (baseData.member != null) {
    //             for (let key in baseData.member) {
    //                 let item: MemberData = baseData.member[key]
    //                 if (item.name == name) {
    //                     return baseData.member[item.id]
    //                 }
    //             }
    //         }
    //     }
    //     return null;
    // }

    // public getMemberSetting(baseUrl: string, id: string) {
    //     var baseData: ComponentData = this.getComponentSetting(baseUrl);
    //     if (baseData != null) {
    //         if (baseData.member != null && baseData.member.hasOwnProperty(id)) {
    //             return baseData.member[id]
    //         }
    //     }
    //     return null;
    // }


    // public changeMemberSetting(baseUrl: string, id: string, state: boolean, name: string = "", annotation: string = "") {
    //     if (this.settingData.components == null || !this.settingData.components.hasOwnProperty(baseUrl)) {
    //         console.error("父节点未设置参数，设置退出 baseUrl=" + baseUrl)
    //         return
    //     }
    //     let isChange = false
    //     let com: ComponentData = this.settingData.components[baseUrl]
    //     let mem: MemberData = null
    //     if (!com.member.hasOwnProperty(id)) {
    //         mem = new MemberData();
    //         //新建
    //         com.member[id] = mem;
    //         isChange = true
    //     } else {
    //         mem = com.member[id]
    //         if (mem.name != name || mem.useCustomScript != state || mem.annotation != annotation) {
    //             isChange = true
    //         }
    //     }
    //     if (isChange) {
    //         mem.id = id
    //         mem.name = name
    //         mem.useCustomScript = state
    //         mem.annotation = annotation
    //         this.save(baseUrl)
    //     }
    // }

    //获取所有的文件的路径
    public getAllDirector(path: string, list: Array<string>) {
        let files = Directory.GetFiles(path, "*.json")
        console.log("开始读取所有配置=", path)
        for (let f = 0; f < files.Length; f++) {
            list.push(files.get_Item(f))
        }
    }
    public readAll() {
        try {
            let list: Array<string> = []
            this.getAllDirector(this.componentsSettingBasePath, list)
            console.log("初始化所有配置,count=", list.length)
            this.settingData = new GenCodeSettingData();
            this.settingData.components = {}
            for (let index = 0; index < list.length; index++) {
                let p = list[index];
                if (p === undefined) continue;
                let jsonStr = File.ReadAllText(p);
                let data: ComponentData = JSON.parse(jsonStr);
                let url = data.url
                this.settingData.components[url] = data
            }
        } catch (err) {
            console.error("读取配置文件失败=", err)
        }
    }

    public delete(url: string) {
        let path = this.componentsSettingBasePath + "/" + this.urlDecode(url) + ".json";
        File.Delete(url)
    }

    public save(url: string) {
        try {
            if (this.settingData.components != null && this.settingData.components.hasOwnProperty(url)) {
                let path = this.componentsSettingBasePath + "/" + this.urlDecode(url) + ".json";
                let data = this.settingData.components[url]
                let jsonStr = JSON.stringify(data);
                File.WriteAllText(path, jsonStr)
                console.log("配置文件更新:" + url)
            } else {
                console.error("要保存的配置不存在：" + url)
            }
        } catch {
            console.error("保存配置文件失败")
        }
    }

    public urlDecode(url: string) {
        return url.replace("ui://", "")
    }
}


export default GenCodeSettings.getInstance();

