sendMessage method

Future<ChatMessage> sendMessage(
  1. String text, {
  2. String? attachmentUrl,
  3. String? attachmentName,
  4. String? attachmentType,
})

Sends a message to the current receiver

Implementation

Future<ChatMessage> sendMessage(
  String text, {
  String? attachmentUrl,
  String? attachmentName,
  String? attachmentType,
}) async {
  // Use custom handler if provided
  if (_apiHandlers?.sendMessageHandler != null) {
    try {
      final message = await _apiHandlers!.sendMessageHandler!(text);
      _messages.add(message);
      _triggerEvent(ChatEventType.messagesChanged, _messages);
      return message;
    } catch (e) {
      _log('Error in custom sendMessageHandler: $e');
      _triggerEvent(ChatEventType.error, 'Failed to send message: $e');
      rethrow;
    }
  }

  // Otherwise use default implementation
  final userId = ChatConfig.instance.userId;
  if (_socket == null ||
      !_socket!.connected ||
      userId == null ||
      _receiverId.isEmpty) {
    throw Exception(
        'Cannot send message: socket not connected or IDs missing');
  }

  // Stop typing indicator
  sendTypingIndicator(false);

  String messageId = DateTime.now().millisecondsSinceEpoch.toString();
  String roomId = getRoomId(userId, _receiverId);

  final message = ChatMessage(
    messageId: messageId,
    senderId: userId,
    receiverId: _receiverId,
    message: text,
    createdAt: DateTime.now(),
    status: 'sent',
    isMine: true,
    attachmentUrl: attachmentUrl,
    attachmentName: attachmentName,
    attachmentType: attachmentType,
  );

  _log('Sending message: ${message.toMap()}');
  _socket!.emit(_socketEvents.sendMessageEvent, {
    ...message.toMap(),
    'roomId': roomId,
  });

  // Add message to local list
  _messages.add(message);
  _triggerEvent(ChatEventType.messagesChanged, _messages);

  return message;
}