import { _decorator, Component, Label, log, error} from "cc";
import { EDITOR } from "cc/env";
import i18n from "./LanguageData";
import { Logger } from "../../../extend/Logger";
const { ccclass, property } = _decorator;

/**
 * 1、lable多语言 直接挂载LocalizedLabel类 到lable节点上 然后填入id，
   这个id是多语言中i18n.languages.en 例如
   "lottery": {
        "title": "Wheel of fortune",
        "free": "Free"
    },就是 填入“lottery.title”

    2、打当lable文本是动态的时候，比如”你完成了多少个个订单“ 这儿就需要你在当前所在的类的，
    就是这个空间的所在的页面调用 this.lbTakeCount.string = i18n("balance.你完成了%{value}个订单", { value: take});
    传入动态的实际参数，然后在这个lable上就不需要在去挂载 LocalizedLabel类

    以上总结：就是静态的多语言文本需要挂载 LocalizedLabel类
    而动态的不需要挂载，直接在当前的文本类里设置动态的多语言
 */
@ccclass("LocalizedLabel")
export default class LocalizedLabel extends Component {
    _debouncedUpdateLabel: any = null;
    label: Label | null = null;
    static editor = {
        executeInEditMode: true,
        menu: 'i18n/LocalizedLabel'
    }
    @property
    _dataID = "";

    @property
    set dataID (val: string) {
        if (this._dataID !== val) {
            this._dataID = val;
            if (EDITOR) {
                this._debouncedUpdateLabel && this._debouncedUpdateLabel();
            } else {
                this.updateLabel();
            }
        }
    }

    get dataID() {
        return this._dataID;
    }

    public onLoad () {
        if(EDITOR) {
            this._debouncedUpdateLabel = this.debounce(this.updateLabel, 200);
        }
        if (!i18n.inst) {
            i18n.init();
        }
        Logger.log('dataID: ' + this.dataID + ' value: ' + i18n(this.dataID));
        this.fetchRender();
    }

    public fetchRender () {
        let label = this.getComponent(Label);
        if (label) {
            this.label = label;
            this.updateLabel();
            return;
        }
    }

    public updateLabel () {
        if (!this.label) {
            error('Failed to update localized label, label component is invalid!');
            return;
        }
        let localizedString = i18n(this.dataID, {});
        if (localizedString) {
            this.label.string = i18n(this.dataID, {});
        }
    }

    public debounce(func: Function, wait: number, immediate ?: number) {
        let timeout = -1;
        return (() => {
            const args = arguments;
            const later = (() => {
                timeout = -1;
                if (!immediate) func.apply(this, args);
            }).bind(this);
            const callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(this, args);
        }).bind(this);
    }
}
