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

@Provide()
@Scope(ScopeEnum.Singleton)
export class SqliteDataSourceManager extends DataSourceManager<sqlite3.Database> {
  options = {
    dataSource: {
      // dataSource0: {
      //   // database: './src/xj.j3tiles',
      //   // database: resolve('D:/jtcim/dist/xj.j3tiles'),
      //   database: './src/11294.3dtiles',
      // },
    },
    // 其他配置
  };
  @Inject()
  baseDir: string;
  @InjectEntityModel(DataSourceEntity)
  dataSourceEntity: Repository<DataSourceEntity>;
  @Init()
  async init() {
    const dataSources = await this.dataSourceEntity.find({
      where: { type: 3 },
    });
    dataSources.map(e => {
      const dataSource = {
        database: resolve(e.database),
      };
      this.options.dataSource['dataSource' + e.id] = dataSource;
    });
    await this.initDataSource(this.options, this.baseDir);
  }
  //创建单个实例
  public async createDataSource(
    config: any,
    dataSourceName: string
  ): Promise<sqlite3.Database> {
    return new sqlite3.Database(config.database);
  }

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

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

  protected async destroyDataSource(
    dataSource: sqlite3.Database
  ): Promise<void> {
    if (await this.checkConnected(dataSource)) {
      await dataSource.close();
    }
  }
}
