import { Init, Inject, Provide, Scope, ScopeEnum } from '@midwayjs/decorator';
import { DataSourceManager } from '@midwayjs/core';
import * as mysql from 'mysql2';
import { DataSourceEntity } from '../entity/sys/data_source';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';

@Provide()
@Scope(ScopeEnum.Singleton)
export class MySqlDataSourceManager extends DataSourceManager<mysql.Pool> {
  options = {
    dataSource: {
      // dataSource0: {
      //   host: '127.0.0.1',
      //   port: 3306,
      //   user: 'root',
      //   password: '123456',
      //   database: 'cr-mysql',
      // },
    },
    // 其他配置
  };
  @Inject()
  baseDir: string;
  @InjectEntityModel(DataSourceEntity)
  dataSourceEntity: Repository<DataSourceEntity>;
  @Init()
  async init() {
    const dataSources = await this.dataSourceEntity.find({
      where: { type: 2 },
    });
    dataSources.map(e => {
      const dataSource = {
        host: e.host,
        port: e.port,
        user: e.user,
        password: e.password,
        database: e.database,
      };
      this.options.dataSource['dataSource' + e.id] = dataSource;
    });
    await this.initDataSource(this.options, this.baseDir);
  }
  //创建单个实例
  public async createDataSource(
    config: any,
    dataSourceName: string
  ): Promise<mysql.Pool> {
    return mysql.createPool(config);
  }

  getName(): string {
    return 'mysql';
  }

  protected async checkConnected(dataSource: mysql.Pool): Promise<boolean> {
    //伪代码
    // return dataSource.status === 'connected';
    return true;
  }

  protected async destroyDataSource(dataSource: mysql.Pool): Promise<void> {
    if (await this.checkConnected(dataSource)) {
      dataSource.end();
    }
  }
}
