/*
 * Fish Integration Service - 用于初始化和管理Fish API集成
 */

import {userInfoService} from './userInfoService';
import {logger} from '../logger';

export class FishIntegrationService {
  private static instance: FishIntegrationService;
  private log = logger('[fish-integration-service]');
  private initialized = false;

  private constructor() {}

  public static getInstance(): FishIntegrationService {
    if(!FishIntegrationService.instance) {
      FishIntegrationService.instance = new FishIntegrationService();
    }
    return FishIntegrationService.instance;
  }

  /**
   * 初始化Fish集成服务
   */
  public async initialize(appManagers: any) {
    if(this.initialized) {
      this.log('Fish集成服务已经初始化');
      return;
    }

    try {
      // 设置UserInfoService的AppManagers
      userInfoService.setAppManagers(appManagers);

      this.initialized = true;
      this.log('Fish集成服务初始化成功');

      // 监听用户登录事件
      this.setupEventListeners(appManagers);
    } catch(error) {
      this.log.error('Fish集成服务初始化失败:', error);
    }
  }

  /**
   * 设置事件监听器
   */
  private setupEventListeners(appManagers: any) {
    try {
      // 这里可以添加各种事件监听器
      // 例如：用户登录、账户切换等事件
      this.log('设置事件监听器...');

      this.log('事件监听器设置完成');
    } catch(error) {
      this.log.error('设置事件监听器失败:', error);
    }
  }

  /**
   * 手动同步当前用户数据
   */
  public async syncCurrentUser() {
    if(!this.initialized) {
      this.log.warn('Fish集成服务未初始化');
      return {success: false, message: '服务未初始化'};
    }

    try {
      // 这里需要获取当前账户号，暂时使用1
      const accountNumber = 1 as any;
      const userId = 'current_user'; // 这里需要从AppManagers获取当前用户ID
      const sessionData = 'current_session'; // 这里需要获取当前会话数据

      const result = await userInfoService.syncUserToBackend(
        accountNumber,
        userId,
        sessionData
      );

      return result;
    } catch(error) {
      this.log.error('同步当前用户数据失败:', error);
      return {success: false, message: error instanceof Error ? error.message : '未知错误'};
    }
  }

  /**
   * 检查服务是否已初始化
   */
  public isInitialized(): boolean {
    return this.initialized;
  }
}

// 创建单例实例
export const fishIntegrationService = FishIntegrationService.getInstance();
