initGlobalConnection method

Future<void> initGlobalConnection()

Implementation

Future<void> initGlobalConnection() async {
  if (_isInitializingGlobalConnection) {
    _log('Global connection initialization already in progress');
    return;
  }

  _isInitializingGlobalConnection = true;

  try {
    // First check if socket is already connected
    if (_socket != null && _socket!.connected) {
      _log('Socket already connected, refreshing global listeners');
      _receiverId = ""; // Clear receiver ID for global mode

      // Re-register for global notifications
      final userId = ChatConfig.instance.userId;
      if (userId != null) {
        _socket!.emit(_socketEvents.registerUserEvent, {'userId': userId});
      }

      // Refresh chat rooms
      await loadChatRooms();

      _isInitializingGlobalConnection = false;
      return;
    }

    // If socket exists but is disconnected, reconnect it
    if (_socket != null) {
      _log('Socket exists but disconnected, reconnecting...');
      _socket!.connect();
      _isInitializingGlobalConnection = false;
      return;
    }

    // Otherwise create a new socket
    _receiverId = ""; // Clear receiver ID for global mode
    await _initializeSocketConnection(isGlobal: true);
  } finally {
    _isInitializingGlobalConnection = false;
  }
}