/**
 * 翻译字典
 * 
 * @param {string} locale 语言
 */
class I18nBook {
    constructor(locale) {
        this.locale = locale;
        // TODO: 修改翻译后请更新版本号
        this.version = "202306281444";
    }
    static _sourceMap = {
        "zh": "zh_cn",
        "zh-tw": "zh_cn",
        "en": "en_us",
    }
    /**
     * 切换语言
     * @param {string} locale 语言，格式：zh-cn 或 zh
     */
    static async changeLocale(locale) {
        var ins = new I18nBook(locale);
        await ins.load();
        ins.apply(document.body);
        return ins;
    }

    /**
     * 翻译
     * @param {string} key 
     */
    translate(key) {
        if (!this._data) return key;
        var content = this._data[key];
        return content || key;
    }

    /**
     * 应用到DOM树种
     * @param {HTMLElement} dom 
     */
    apply(dom) {
        const elements = Array.from($(dom).find("[data-tr-text]"));
        elements.forEach((v, i) => {
            var $v = $(v);
            var key = $v.data("tr-text");
            var content = this.translate(key);
            if (v instanceof HTMLInputElement || v instanceof HTMLTextAreaElement) {
                v.placeholder = content;
            } else {
                $v.text(content);
            }
        });

        const titleElements = Array.from($(dom).find("[data-tr-title]"));
        titleElements.forEach((v, i) => {
            var $v = $(v);
            var key = $v.data("tr-title");
            var content = this.translate(key);
            v.title = content;
        });
    }

    /**
     * 加载数据
     */
    async load() {
        try {
            const root = findRoot();
            const sourceName = this._matchSourceName();
            var url = `${root}/i18n/${sourceName}.json?v=${this.version}`;
            var data = await $.get(url);
            this._data = data;
        } catch (error) {
            console.log("I18nBook load data error");
            console.log(error);
        }
    }

    _matchSourceName() {
        var map = I18nBook._sourceMap;
        var locale = this.locale.toLowerCase();
        var sourceName = map[locale];
        if (!sourceName) {
            var langCode = locale.split('-')[0];
            sourceName = map[langCode];
        }
        if (!sourceName) {
            sourceName = map['en'];
        }
        return sourceName;
    }
}