/**
 * 车场镜像库
 */

import { logger } from 'mslib';
import { ConfigCenterConfigProvider } from './ConfigCenter';
import Contants, { IS_DEBUG, IS_PROD } from './Contants';
import { IocConfigProvider } from './Config';
import * as Knex from "knex";

/**
 * 车场镜像库knex实例
 * 
 * 如已引用配置依赖[NsConfig](https://me.keytop.cn/service/config)将会自动创建该实例
 * 
 * ```ts
 * import { parkImageKnexInstance } from "refs/nslib";
 * 
 * //使用直接导出的parkImageKnexInstance
 * let res = await parkImageKnexInstance.raw('select * from t_2014_config limit 1');
 * ```
 * @see [mysql2](https://www.npmjs.com/package/mysql2)
 * @see [knex](https://www.npmjs.com/package/knex)
 */
export let knexInstance: Knex<any>;

init();

async function init() {
    try {
        let config = IocConfigProvider.getParkImageMysqlConfig() || await ConfigCenterConfigProvider.getImageMysqlConfig();
        if (!config) return;

        //执行多条语句需开启multipleStatements: true
        config = Object.assign({ multipleStatements: true }, config);
        knexInstance = generateMySqlKnexInstance({ connection: config });

        logger.info(`车场镜像knex实例创建成功,host:${config.host}`);
    } catch (error) {
        logger.error('车场镜像knex实例创建失败', error);
    }
}

export function generateMySqlKnexInstance(config) {
    const defaults = {
        client: 'mysql2',
        debug: IS_DEBUG,
        log: {
            warn(message) {
                // logger.warn(message);
            },
            error(message) {
                logger.error(message);
            },
            deprecate(message) {
                logger.error(message);
            },
            debug(message) {
                logger.debug(message);
            },
        }
    };

    return Knex(Object.assign(defaults, config));
}