import 'package:taafee_mobile/core/utils/pagination_list.dart';
import 'package:taafee_mobile/features/chat/data_layer/model/chat_user.dart';
import 'package:taafee_mobile/features/chat/data_layer/model/message.dart';

class Room {
  int id;
  RoomType type;
  ChatUser? user;
  RoomState state;
  MessageModel? lastMessage;
  DateTime lastMessageDate;
  Pagination<MessageModel> messages = Pagination();

  String? messagesStateId;

  // @constructors
  Room({
    required this.id,
    this.type = RoomType.private,
    required this.user,
    required this.lastMessageDate,
    this.state = RoomState.active,
    this.lastMessage,
  });

  factory Room.fromJson(Map<String, dynamic> jsonMap) => Room(
        id: jsonMap["id"],
        type: (jsonMap["type"] == "private")
            ? RoomType.private
            : RoomType.support,
        user: jsonMap["Users"] != null
            ? ChatUser.fromJson(jsonMap["Users"][0])
            : null,
        lastMessageDate: DateTime.parse(jsonMap['lastMessageDate']).toLocal(),
        lastMessage:
            (jsonMap["Messages"] != null && jsonMap["Messages"].isNotEmpty)
                ? MessageModel.fromJson(jsonMap["Messages"][0])
                : null,
        state: getRoomStateByString(
                jsonMap["Users"]?[0]?["user_status"]?["status"]) ??
            RoomState.active,
      );
  static List<Room> fromJsonList(List jsonList) {
    List<Room> rooms = [];
    // ignore: avoid_function_literals_in_foreach_calls
    jsonList.forEach((element) {
      if (element["type"] == "private") {
        rooms.add(Room.fromJson(element));
      }
    });
    return rooms;
  }

  static RoomState? getRoomStateByString(String? state) {
    switch (state) {
      case 'active':
        return RoomState.active;
      case 'blocking':
        return RoomState.blocking;
      case 'blocked':
        return RoomState.blocked;
    }
    return null;
  }

  factory Room.copy(Room room) =>
      Room(id: room.id, user: room.user, lastMessageDate: room.lastMessageDate);
}

enum RoomType { private, support }

enum RoomState { active, blocked, blocking }
