// 数据源工厂类
import { DataSource } from './DataSource';
import { TQDataSource } from './TQDataSource';
import { logger } from '../../utils/logger';

// 数据源类型
export enum DataSourceType {
  TQSDK = 'tqsdk',
  MOCK = 'mock',
  WIND = 'wind',
  SINA = 'sina',
  TEST = 'test'
}

export class DataSourceFactory {
  private static dataSources: Map<DataSourceType, DataSource> = new Map();

  // 获取数据源实例
  static async getDataSource(type: DataSourceType = DataSourceType.TQSDK, config: any = {}): Promise<DataSource> {
    logger.log('获取数据源实例:', type);
    if (!this.dataSources.has(type)) {
      let dataSource: DataSource;
      
      switch (type) {
        case DataSourceType.TQSDK:
          dataSource = new TQDataSource(config.tqsdk || {});
          break;
        case DataSourceType.MOCK:
        case DataSourceType.TEST:
          // 导入模拟数据源
          const { MockDataSource } = await import('./MockDataSource');
          dataSource = new MockDataSource();
          break;
        default:
          throw new Error(`不支持的数据源类型: ${type}`);
      }
      
      // 初始化数据源
      const initialized = await dataSource.initialize();
      if (!initialized) {
        throw new Error(`数据源${type}初始化失败`);
      }
      
      this.dataSources.set(type, dataSource);
    }
    
    return this.dataSources.get(type)!;
  }

  // 关闭所有数据源
  static async closeAllDataSources(): Promise<void> {
    for (const [type, dataSource] of this.dataSources) {
      try {
        await dataSource.close();
        logger.log(`数据源${type}已关闭`);
      } catch (error) {
        logger.error(`关闭数据源${type}失败:`, error);
      }
    }
    this.dataSources.clear();
  }

  // 切换数据源
  static async switchDataSource(type: DataSourceType): Promise<DataSource> {
    // 关闭当前数据源
    await this.closeAllDataSources();
    // 获取新数据源
    return this.getDataSource(type);
  }
}