/**
 * 车场镜像库
 */

import { logger } from "mslib";
import { ConfigCenterConfigProvider } from "./ConfigCenter";
import Contants, { IS_DEBUG, IS_PROD } from "./Contants";

/**
 * 车场镜像库knex实例
 * 
 * https://www.npmjs.com/package/knex
 */
export let knexInstance = null;

init();

async function init() {
    try {
        let config = 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',
        acquireConnectionTimeout: 5000,
        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 require('knex')(Object.assign(defaults, config));
}