class WebSocketService {
  constructor(url, options = {}) {
    this.url = url;
    this.ws = null;
    this.reconnectInterval = options.reconnectInterval || 3000;
    this.maxReconnectAttempts = options.maxReconnectAttempts || 10;
    this.reconnectAttempts = 0;
    this.eventListeners = {};
    this.isManuallyClosed = false;
    this.connect();
  }

  connect() {
    this.ws = new window.WebSocket(this.url);
    this.ws.onopen = (event) => {
      this.reconnectAttempts = 0;
      this.emit('open', event);
    };
    this.ws.onmessage = (event) => {
      this.emit('message', event.data);
    };
    this.ws.onerror = (event) => {
      this.emit('error', event);
    };
    this.ws.onclose = (event) => {
      this.emit('close', event);
      if (!this.isManuallyClosed) {
        this.reconnect();
      }
    };
  }

  reconnect() {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      setTimeout(() => {
        this.reconnectAttempts++;
        this.connect();
      }, this.reconnectInterval);
    } else {
      this.emit('reconnect_failed');
    }
  }

  send(data) {
    if (this.ws && this.ws.readyState === window.WebSocket.OPEN) {
      this.ws.send(typeof data === 'string' ? data : JSON.stringify(data));
    } else {
      this.emit('send_failed', data);
    }
  }

  close() {
    this.isManuallyClosed = true;
    if (this.ws) {
      this.ws.close();
    }
  }

  on(event, callback) {
    if (!this.eventListeners[event]) {
      this.eventListeners[event] = [];
    }
    this.eventListeners[event].push(callback);
  }

  off(event, callback) {
    if (!this.eventListeners[event]) return;
    this.eventListeners[event] = this.eventListeners[event].filter(cb => cb !== callback);
  }

  emit(event, ...args) {
    if (this.eventListeners[event]) {
      this.eventListeners[event].forEach(cb => cb(...args));
    }
  }
}

// 单例模式，方便全局使用
let wsInstance = null;

export function createWebSocket(url, options) {
  if (!wsInstance) {
    wsInstance = new WebSocketService(url, options);
  } else if (wsInstance.url !== url) {
    // 如果URL改变，重新创建实例
    wsInstance.close();
    wsInstance = new WebSocketService(url, options);
  }
  return wsInstance;
}

// 重置WebSocket实例，用于强制重新创建实例
export function resetWebSocketInstance() {
  if (wsInstance) {
    wsInstance.close();
    wsInstance = null;
  }
}

export default WebSocketService; 