"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const path = require("path");
const no_cache_require_1 = require("../utils/no-cache-require");
const tapable_1 = require("tapable");
class IntlStorage {
    constructor(config) {
        this.config = config;
        this.hooks = {
            storeKeyToFile: new tapable_1.AsyncSeriesWaterfallHook(['listeners'])
        };
    }
    initLang() {
        this.initFilesIfNotExist(this.config.langs);
    }
    updateKeyInLang(param) {
        Object.keys(param).forEach((langKey, values) => {
            const langFile = this.getLangFile(langKey);
            const result = no_cache_require_1.default(langFile);
            const newResult = JSON.stringify(Object.assign(result, values), null, 4);
            fs.writeFileSync(langFile, this.config.fileExt === 'json' ? newResult : `module.exports = ${newResult}`);
        });
    }
    checkKeyInLang(key, lang, text) {
        const langFile = this.getLangFile(lang);
        const result = no_cache_require_1.default(langFile);
        return {
            exist: !!result[key],
            ananimous: result[key] === text
        };
    }
    getValueKeyInLang(value, lang) {
        const langFile = this.getLangFile(lang);
        const result = no_cache_require_1.default(langFile);
        var keyString = null;
        Object.keys(result).forEach((key) => {
            if (result[key] === value) {
                keyString = key;
            }
        });
        return keyString;
    }
    checkKey(key, text) {
        var result = {};
        this.config.langs.forEach(lang => {
            if (lang.check) {
                result[lang.key] = this.checkKeyInLang(key, lang.key, text);
            }
        });
        return result;
    }
    getValueKey(value) {
        var result = {};
        this.config.langs.forEach(lang => {
            if (lang.check) {
                result[lang.key] = this.getValueKeyInLang(value, lang.key);
            }
        });
        return result;
    }
    storeKeyAndValues(addParams) {
        return __awaiter(this, void 0, void 0, function* () {
            // 以lang为索引，合并key
            // @ts-ignore
            const langs = {};
            const keyMap = {};
            addParams.forEach((addItem) => {
                if (!langs[addItem.lang]) {
                    langs[addItem.lang] = {};
                }
                langs[addItem.lang][addItem.key] = addItem.text;
                if (!keyMap[addItem.key]) {
                    // @ts-ignore
                    keyMap[addItem.key] = {
                        [addItem.lang]: addItem.text
                    };
                }
                else {
                    keyMap[addItem.key][addItem.lang] = addItem.text;
                }
            });
            const listeners = yield this.hooks.storeKeyToFile.promise([]);
            const keys = Object.keys(keyMap);
            for (var i = 0, len = keys.length; i < len; i++) {
                for (var j = 0, jlen = listeners.length; j < jlen; j++) {
                    const callback = listeners[j];
                    yield callback(keys[i], keyMap[keys[i]]);
                }
            }
            // @ts-ignore
            Object.keys(langs).forEach((langKey) => __awaiter(this, void 0, void 0, function* () {
                this.writeLangKeysToFile(langKey, langs[langKey]);
            }));
        });
    }
    writeLangKeysToFile(langLey, keys, isWhoile = false) {
        var writeInfo = keys;
        const langFile = this.getLangFile(langLey);
        if (!isWhoile) {
            const result = no_cache_require_1.default(langFile);
            writeInfo = Object.assign(Object.assign({}, result), keys);
        }
        const keyString = JSON.stringify(writeInfo, null, 4);
        fs.writeFileSync(langFile, this.config.fileExt === 'js' ? `module.exports=${keyString}` : keyString);
    }
    storeKeyAndValue(addParam) {
        this.storeKeyAndValues([addParam]);
    }
    getKeyInLang(key, lang) {
        const langFile = this.getLangFile(lang);
        const result = no_cache_require_1.default(langFile);
        return result[key];
    }
    getLangFile(lang) {
        const langFile = path.join(this.config.localeDir, `${lang}.${this.config.fileExt}`);
        return langFile;
    }
    initFilesIfNotExist(langs) {
        langs.forEach(lang => {
            const langFile = this.getLangFile(lang.key);
            if (!fs.existsSync(langFile)) {
                fs.writeFileSync(langFile, this.config.fileExt === 'js' ? `module.exports={}` : '{}');
            }
        });
    }
}
exports.default = IntlStorage;
//# sourceMappingURL=IntlStorage.js.map