class NameSpaceManager {
  constructor(io) {
    this.io = io;
    this.userNamespaces = new Map();
    this.driverNamespaces = new Map();
    this.chatNamespaces = new Map();
  }

  _createNamespace(namespacePath, namespaceMap) {
    const namespace = this.io.of(namespacePath);
    console.log(namespaceMap, "namespaceMap");
    console.log(namespacePath, "namespacePath");
    namespaceMap.set(namespacePath.split("/")[0], namespace);
    return namespace;
  }

  createUserNamespace(userId) {
    console.log("userId:",userId);
    
    return this._createNamespace(
      `/userNamespace/${userId}`,
      this.userNamespaces,
    );
  }

  createDriverNamespace(driverId) {
    return this._createNamespace(
      `/driverNamespace/${driverId}`,
      this.driverNamespaces,
    );
  }

  getUserNamespace(userId) {
    return this.userNamespaces.get(userId);
  }

  getDriverNamespace(driverId) {
    return this.driverNamespaces.get(driverId);
  }

  getAllConnectedDrivers() {
    return Array.from(this.driverNamespaces.values());
  }

  getAllConnectedUsers() {
    return Array.from(this.userNamespaces.entries())
      .filter(([, namespace]) => namespace.connected)
      .map(([userId]) => userId);
  }

  _disconnectNamespace(namespaceMap, id) {
    const namespace = namespaceMap.get(id);
    if (namespace) {
      namespace.sockets.forEach((socket) => socket.disconnect(true));
      // namespace.delete(id);
    }
  }

  disconnectUserNamespace(userId) {
    this._disconnectNamespace(this.userNamespaces, userId);
  }

  disconnectDriverNamespace(driverId) {
    this._disconnectNamespace(this.driverNamespaces, driverId);
  }

  _destroyNamespace(namespaceMap, id) {
    this._disconnectNamespace(namespaceMap, id);
    const namespace = namespaceMap.get(id);
    if (namespace) {
      namespace.removeAllListeners();
      // namespaceMap.delete(id);
    }
  }

  destroyUserNamespace(userID) {
    this._destroyNamespace(this.userNamespaces, userID);
  }

  destroyDriverNamespace(driverID) {
    this._destroyNamespace(this.driverNamespaces, driverID);
  }

  createChatNamespace(chatId) {
    return this._createNamespace(`/chatNamespace/${chatId}`, this.chatNamespaces);
  }
  destroyChatNamespace(chatID) {
    this._destroyNamespace(this.chatNamespaces, chatID);
  }
}
export default NameSpaceManager;
