"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());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.t = exports.i18n = exports.DEFAULT_LOCALE = void 0;
var typescript_ioc_1 = require("typescript-ioc");
var mslib_1 = require("mslib");
var Redis_1 = require("./Redis");
var Contants_1 = require("./Contants");
var Decorators_1 = require("./Decorators");
/**
 * 翻译插件
 * @date 2022-07-12 13:28:45
 * @author 许婷婷
 */
var Translator = /** @class */ (function () {
    function Translator() {
    }
    return Translator;
}());
exports.DEFAULT_LOCALE = 'zh_CN';
/**
 * i18n国际化实例
 *
 * 模块被加载时，从ioc读取配置config.global并自动创建该实例+初始化，如果未配置则为空
 *
 * 用法：
 *
 * i18n.__('(主相机)')
 *
 * i18n.__('Hello %s', 'Keytop')
 *
 * i18n.__('Hello {0}', ['Keytop'])
 *
 * i18n.__('Hello {name}', { name: 'Keytop' })
 *
 * i18n.__({ phrase: 'Hello %s', locale: 'en_US' }, 'Keytop1')
 *
 * i18n.__({ phrase: 'Hello {0}', locale: 'en_US' }, ['Keytop1'])
 *
 * i18n.__({ phrase: 'Hello {name}', locale: 'en_US' }, { name: 'Keytop1' })
 *
 * https://www.npmjs.com/package/i18n
 */
exports.i18n = null;
var config = typescript_ioc_1.Container.getValue('config.global');
/**
 * 加载语言包，定时10分钟刷新一次语言包
 */
// config?.enabled 是否开启国际化
if ((config === null || config === void 0 ? void 0 : config.enabled) === true) {
    var I18n = require('i18n').I18n;
    exports.i18n = new I18n();
    setTimeout(function () { return __awaiter(void 0, void 0, void 0, function () {
        var error_1;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 2, , 3]);
                    return [4 /*yield*/, Decorators_1.retry(function () { return __awaiter(void 0, void 0, void 0, function () {
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0: return [4 /*yield*/, configure_i18n()];
                                    case 1:
                                        _a.sent();
                                        mslib_1.logger.info('i18n配置成功');
                                        return [2 /*return*/];
                                }
                            });
                        }); }, 3, 500, {
                            errorHandler: function (error) {
                                mslib_1.logger.error('i18n配置失败', error);
                            }
                        })];
                case 1:
                    _a.sent();
                    return [3 /*break*/, 3];
                case 2:
                    error_1 = _a.sent();
                    mslib_1.logger.error('i18n配置失败', error_1);
                    return [3 /*break*/, 3];
                case 3: return [2 /*return*/];
            }
        });
    }); }, 500);
    setInterval(function () { return __awaiter(void 0, void 0, void 0, function () {
        var error_2;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 2, , 3]);
                    return [4 /*yield*/, configure_i18n()];
                case 1:
                    _a.sent();
                    mslib_1.logger.info('定时刷新i18n配置成功');
                    return [3 /*break*/, 3];
                case 2:
                    error_2 = _a.sent();
                    mslib_1.logger.error('定时刷新i18n配置失败', error_2);
                    return [3 /*break*/, 3];
                case 3: return [2 /*return*/];
            }
        });
    }); }, Contants_1.default.IS_LOCAL_DEBUG ? 1000 * 60 : 1000 * 60 * 10);
}
/**
 * 加载语言包
 */
function configure_i18n() {
    var _a;
    return __awaiter(this, void 0, void 0, function () {
        var packs, _b, staticCatalog, locales, _loop_1, key;
        return __generator(this, function (_c) {
            switch (_c.label) {
                case 0:
                    _b = (_a = config.mode) === null || _a === void 0 ? void 0 : _a.toUpperCase();
                    switch (_b) {
                        case 'CLOUD': return [3 /*break*/, 1];
                        case 'PARK': return [3 /*break*/, 3];
                    }
                    return [3 /*break*/, 5];
                case 1: return [4 /*yield*/, Redis_1.redisClient.hgetall('translation_1102011')];
                case 2:
                    packs = _c.sent();
                    return [3 /*break*/, 5];
                case 3: return [4 /*yield*/, Redis_1.redisClient.hscan('t_realtime_data', { match: "translation_1102011", count: 100 })];
                case 4:
                    // todo 场端redis需要读取设置密码        
                    packs = _c.sent();
                    return [3 /*break*/, 5];
                case 5:
                    staticCatalog = {};
                    locales = [];
                    _loop_1 = function (key) {
                        try {
                            var pack_1 = {};
                            JSON.parse(packs[key]).forEach(function (s) {
                                pack_1[s.key] = s.value;
                            });
                            locales.push(key);
                            staticCatalog[key] = pack_1;
                        }
                        catch (error) {
                            mslib_1.logger.error("\u52A0\u8F7D\u4E91\u7AEFredis\u8BED\u8A00\u5305\u5931\u8D25,lang:" + key, error);
                        }
                    };
                    for (key in packs) {
                        _loop_1(key);
                    }
                    mslib_1.logger.info("\u52A0\u8F7D\u4E91\u7AEFredis\u8BED\u8A00\u5305\u6210\u529F,locale:" + locales.join(','));
                    exports.i18n.configure({
                        // defaultLocale: "zh_CN", // locale 不传，默认按default翻译？
                        locales: locales,
                        staticCatalog: staticCatalog,
                        mustacheConfig: {
                            tags: ['{', '}'],
                            disable: false
                        },
                        logDebugFn: function (msg) {
                            mslib_1.logger.debug(msg);
                        },
                        logWarnFn: function (msg) {
                            // logger.warn(msg);
                        },
                        logErrorFn: function (msg) {
                            mslib_1.logger.error(msg);
                        },
                        missingKeyFn: function (locale, value) {
                            return value;
                        },
                    });
                    return [2 /*return*/];
            }
        });
    });
}
/**
 * 获取翻译语种 header>t_config>中文
 * @param parkId 非必填，主要用于获取车场主语言配置
 * @returns
 */
function getLocale(parkId) {
    var _a;
    var locale = "zh_CN";
    var headers = mslib_1.Context.getRequestHeaders();
    if (headers)
        locale = headers['language']; //如果有前端，则根据前端传入的语种翻译
    if (!locale)
        return locale;
    if (!parkId) {
        var mode = (_a = config.mode) === null || _a === void 0 ? void 0 : _a.toUpperCase(); // cloud 云端程序 park 场端程序
        var rediskey = "lang" + "{{" + parkId + "}}"; // 云端主语言配置项
        if (mode === "PARK")
            locale = "sqlite3"; // 从sqlite读取t_config
        else
            locale = Redis_1.redisClient.get(rediskey); //读取redis,key ：lang-{{parkId}}
    }
    return locale;
}
/**
 * 翻译函数
 *
 * @param data  待翻译的数据
 * @param parkId 非必填，主要用于获取车场主语言配置
 * @returns
 */
function t(data, parkId) {
    if (!data)
        return data;
    var locale = getLocale(parkId);
    if (typeof data === 'object') {
        tObj(data, locale);
        return data;
    }
    else {
        if (typeof data === 'string') {
            return locale ? exports.i18n.__({ phrase: data, locale: locale }) : exports.i18n.__(data);
        }
        else {
            return data;
        }
    }
}
exports.t = t;
function tObj(data, locale) {
    for (var key in data) {
        if (typeof data[key] === 'object') {
            tObj(data[key], locale);
        }
        else {
            if (typeof data[key] === 'string') {
                data[key] = locale ? exports.i18n.__({ phrase: data[key], locale: locale }) : exports.i18n.__(data[key]);
            }
        }
    }
}
//# sourceMappingURL=Translator.js.map