import * as Knex from 'knex'
import { Singleton, Container, Scope, Inject } from "typescript-ioc";
import { Value, logger } from "mslib"

/**
 * 
 * @date 2021-05-27 09:48:32
 * @author 吴锋霖
 */
@Singleton
class KnexFactory {
    private knex: Knex;

    @Value('database.host')
    host: string
    @Value('database.port')
    port: number
    @Value('database.pool.max:1')
    poolMax: string
    @Value('database.pool.min:1')
    poolMin: string
    @Value('database.database')
    database: string
    @Value('database.username')
    username: string
    @Value('database.password')
    password: string


    async init(scheam = 'kt_cn') {
        if (this.knex) {
            return;
        }
        const config = {
            host: this.host,
            user: this.username,
            password: this.password,
            database: this.database,
            port: this.port
        }

        logger.info('准备初始化数据库连接---------->scheam:%j,config:%j,min:%s,max:%s', scheam, config, this.poolMin, this.poolMax)
        this.knex = Knex({
            client: 'pg',
            debug: true,
            searchPath: scheam,
            connection: config,
            pool: { min: parseInt(this.poolMin), max: parseInt(this.poolMax) }
        });
        
        Container.bind(Knex).factory(() => {
            let knexFactory = Container.get(KnexFactory);
            return knexFactory.get();
        }).scope(Scope.Singleton);
        logger.info('初始化数据库连接完成---------->scheam:%j,config:%j,min:%s,max:%s', scheam, config, this.poolMin, this.poolMax)
    }

    get(): Knex {
        return this.knex;
    }
}

export { KnexFactory, Knex }