import { WsEvent, WsEventContext, WsEventListener } from '../types';
import { generateGUID } from '@/utils/common';
import { wsInstance } from './instance';

export interface WsEventManager {
  listeners: Record<string, WsEventListener[]>;
  subscribe(event: WsEvent, handler: Function): WsEventContext;
  unsubscribe(event: WsEvent, listenerId: string): void;
  emit(event: WsEvent, data?: any): void;
}

export class WsEventManagerImpl implements WsEventManager {
  listeners: Record<string, WsEventListener[]> = {};

  subscribe(event: WsEvent, handler: Function): WsEventContext {
    if (!this.listeners[event]) this.listeners[event] = [];

    const listenerId = generateGUID();
    const listener: WsEventListener = { handler, id: listenerId };
    this.listeners[event].push(listener);

    // 立即触发已连接事件
    if (event === WsEvent.CONNECTED && wsInstance?.isConnected.value) {
      handler({
        id: listenerId,
        remove: () => this.unsubscribe(event, listenerId)
      });
    }
    console.log("添加事件去了", event)
    return {
      id: listenerId,
      remove: () => this.unsubscribe(event, listenerId)
    };
  }

  unsubscribe(event: WsEvent, listenerId: string): void {
    if (!this.listeners[event]) return;
    this.listeners[event] = this.listeners[event].filter(l => l.id !== listenerId);
  }

  emit(event: WsEvent, data?: any): void {
    console.debug(`[WS Event] Emitting: ${event}`);
    const listeners = this.listeners[event] || [];
    console.log("事件lieb", listeners)
    // 安全遍历
    listeners.forEach((listener) => {
      const context: WsEventContext = {
        id: listener.id,
        remove: () => this.unsubscribe(event, listener.id)
      };
      listener.handler(context, wsInstance, data);
    });
  }
}

// 单例事件管理器
export const wsEventManager = new WsEventManagerImpl();
