import { Singleton, Container, Scope, Inject } from "typescript-ioc";
import { Context, IService, logger } from "mslib"
import { redisClient } from "./Redis";
import Contants from "./Contants";
import { retry } from "./Decorators";
import { GlobalConfig } from "./Config";


/**
 * 翻译插件
 * @date 2022-07-12 13:28:45
 * @author 许婷婷
 */
class Translator {
}

export let 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
 */
export let i18n = null;

let config: GlobalConfig = Container.getValue('config.global');


/**
 * 加载语言包，定时10分钟刷新一次语言包
 */
// config?.enabled 是否开启国际化
if (config?.enabled === true) {
    const { I18n } = require('i18n');
    i18n = new I18n();

    setTimeout(async () => {
        try {
            await retry(async () => {
                await configure_i18n();
                logger.info('i18n配置成功');
            }, 3, 500, {
                errorHandler: (error) => {
                    logger.error('i18n配置失败', error);
                }
            });
        } catch (error) {
            logger.error('i18n配置失败', error);
        }
    }, 500);

    setInterval(async () => {
        try {
            await configure_i18n();
            logger.info('定时刷新i18n配置成功');
        } catch (error) {
            logger.error('定时刷新i18n配置失败', error);
        }
    }, Contants.IS_LOCAL_DEBUG ? 1000 * 60 : 1000 * 60 * 10);
}

/**
 * 加载语言包
 */
async function configure_i18n() {

    let packs;

    switch (config.mode?.toUpperCase()) {
        case 'CLOUD': // 云端语言包
            packs = await redisClient.hgetall('translation_1102011');
            break;
        case 'PARK': // 场端语言包            
            // todo 场端redis需要读取设置密码        
            packs = await redisClient.hscan('t_realtime_data', { match: "translation_1102011", count: 100 });
            break;
    }

    let staticCatalog = {};
    let locales = [];

    for (const key in packs) {
        try {
            let pack = {};

            JSON.parse(packs[key]).forEach(s => {
                pack[s.key] = s.value;
            });

            locales.push(key);
            staticCatalog[key] = pack;
        } catch (error) {
            logger.error(`加载云端redis语言包失败,lang:${key}`, error);
        }
    }

    logger.info(`加载云端redis语言包成功,locale:${locales.join(',')}`);

    i18n.configure({
       // defaultLocale: "zh_CN", // locale 不传，默认按default翻译？
        locales: locales,
        staticCatalog: staticCatalog,
        mustacheConfig: {
            tags: ['{', '}'],
            disable: false
        },
        logDebugFn: function (msg) {
            logger.debug(msg);
        },
        logWarnFn: function (msg) {
            // logger.warn(msg);
        },
        logErrorFn: function (msg) {
            logger.error(msg);
        },
        missingKeyFn: function (locale, value) {
            return value;
        },
    });
}

/**
 * 获取翻译语种 header>t_config>中文
 * @param parkId 非必填，主要用于获取车场主语言配置 
 * @returns 
 */
function getLocale(parkId?: string): string {

    let locale = "zh_CN";

    let headers = Context.getRequestHeaders();
    if (headers)
        locale = headers['language']; //如果有前端，则根据前端传入的语种翻译
    if (!locale)
        return locale;

    if (!parkId) {
        let mode = config.mode?.toUpperCase(); // cloud 云端程序 park 场端程序
        let rediskey = "lang" + "{{" + parkId + "}}"; // 云端主语言配置项
        if (mode === "PARK")
            locale = "sqlite3"; // 从sqlite读取t_config
        else
            locale = redisClient.get(rediskey); //读取redis,key ：lang-{{parkId}}
    }


    return locale;
}

/**
 * 翻译函数
 * 
 * @param data  待翻译的数据
 * @param parkId 非必填，主要用于获取车场主语言配置 
 * @returns 
 */
export function t(data: any, parkId?: string) {

    if (!data) return data;

    let locale = getLocale(parkId);

    if (typeof data === 'object') {
        tObj(data, locale);
        return data;
    } else {
        if (typeof data === 'string') {
            return locale ? i18n.__({ phrase: data, locale: locale }) : i18n.__(data);
        } else {
            return data;
        }
    }
}

function tObj(data: object, locale?: string) {
    for (const key in data) {
        if (typeof data[key] === 'object') {
            tObj(data[key], locale);
        } else {
            if (typeof data[key] === 'string') {
                data[key] = locale ? i18n.__({ phrase: data[key], locale: locale }) : i18n.__(data[key]);
            }
        }
    }
}

