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

@Provide()
@Scope(ScopeEnum.Singleton)
export class PgDataSourceManager extends DataSourceManager<pg.Pool> {
  @Config('typeorm')
  pgConfig;
  options = {
    dataSource: {
      // dataSource0: {
      //   host: '127.0.0.1',
      //   port: 5432,
      //   user: 'postgres',
      //   password: 'mysecretpassword',
      //   database: 'cr',
      // },
    },
    // 其他配置
  };
  @Inject()
  baseDir: string;
  @InjectEntityModel(DataSourceEntity)
  dataSourceEntity: Repository<DataSourceEntity>;
  @Init()
  async init() {
    const dataSources = await this.dataSourceEntity.find({
      where: { type: 1 },
    });
    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;
    });
    const dataSource0 = {
      host: this.pgConfig.dataSource.default.host,
      port: this.pgConfig.dataSource.default.port,
      user: this.pgConfig.dataSource.default.username,
      password: this.pgConfig.dataSource.default.password,
      database: this.pgConfig.dataSource.default.database,
    };
    this.options.dataSource['dataSource0'] = dataSource0;

    await this.initDataSource(this.options, this.baseDir);
  }
  //创建单个实例
  protected async createDataSource(
    config: any,
    dataSourceName: string
  ): Promise<pg.Pool> {
    return new pg.Pool(config);
  }

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

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

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