import { DisplayMessage } from "@/store/messagesStore";
import { ChatMessageTypes } from "@/types/chatMessageTypes";
import { eRole } from "@/types/roleType";
import ChatDataService from "@/utils/ChatDataService";
import {
  getMasterIdFromDisplayMsg,
  getTargetIdFromDisplayMsg,
} from "@/utils/chatutils";
import { getUserMsg } from "@/utils/userMsg";
import { iChatListCard, MyAppDatabase } from "./index";

export default class ChatListCardDB extends MyAppDatabase {
  static instance: ChatListCardDB;
  static getInstance() {
    if (!ChatListCardDB.instance) {
      ChatListCardDB.instance = new ChatListCardDB();
    }
    return ChatListCardDB.instance;
  }

  saveCard(item: iChatListCard) {
    return this.chatListCard.add({ ...item });
  }

  deleteCard(masterId: string, targetId: string) {
    return this.chatListCard
      .filter((item) => {
        return item.masterId === masterId && targetId === item.targetId;
      })
      .delete();
  }

  updateCard(
    masterId: string,
    targetId: string,
    count: number,
    content: string,
    datetime: number
  ) {
    this.chatListCard
      .filter((item) => {
        return item.masterId === masterId && targetId === item.targetId;
      })
      .modify((item) => {
        item.unreadMsgCount = count;
        item.content = content;
        item.datetime = datetime;
      });
  }

  getCardList(masterId: string) {
    return this.chatListCard
      .filter((item) => {
        return item.masterId === masterId;
      })
      .reverse()
      .sortBy("datetime");
  }

  async thePersonAlreadyInChatList(masterId: string, personId: string) {
    return (
      (await this.chatListCard
        .filter((i) => i.targetId === personId && i.masterId === masterId)
        .count()) !== 0
    );
  }

  async updateNewestCard(data: {
    msg: DisplayMessage;
    isChattingWithTargetId: boolean;
  }) {
    const { msg, isChattingWithTargetId } = data;
    const targetId = getTargetIdFromDisplayMsg(msg);
    const masterId = getMasterIdFromDisplayMsg(msg);

    const cardItem = await this.chatListCard
      .filter((item) => {
        return item.masterId === masterId && item.targetId === targetId;
      })
      .first();

    let content: string;
    if (msg.type === ChatMessageTypes.Card) {
      content =
        ChatDataService.getInstance().extractCommonMsgContentFromMsg(
          msg,
          getUserMsg()?.role2 as eRole
        ) || "";
    } else {
      content = msg.content?.content || "[新消息]";
    }

    const unreadMsgCount = cardItem?.unreadMsgCount || 0;

    console.log(data.msg, "show msg when update newest card");

    this.updateCard(
      masterId,
      targetId,
      isChattingWithTargetId ? 0 : unreadMsgCount + 1,
      content,
      data.msg.datetime
    );
  }

  async addNewCard(data: {
    msg: DisplayMessage;
    isChattingWithTargetId: boolean;
    isRobootCard?: boolean;
  }) {
    const content = data.msg.content?.content || "[新消息]";
    const masterId = getMasterIdFromDisplayMsg(data.msg);
    const targetId = getTargetIdFromDisplayMsg(data.msg);
    console.log(data.msg, "in addNewCard");

    this.saveCard({
      masterId,
      targetId: targetId,
      unreadMsgCount: data.isChattingWithTargetId ? 0 : 1,
      content,
      inChat: false,
      datetime: data.msg.datetime,
      isRobootCard: data.isRobootCard,
    });
  }

  readMsg(masterId: string, targetId: string) {
    return this.chatListCard
      .filter((item) => {
        return item.targetId === targetId && item.masterId === masterId;
      })
      .modify((item) => {
        item.unreadMsgCount = 0;
      });
  }

  setChatStatus(masterId: string, targetId: string, isChat: boolean) {
    return this.chatListCard
      .filter((item) => {
        return item.targetId === targetId && item.masterId === masterId;
      })
      .modify((item) => {
        item.inChat = isChat;
      });
  }

  async getChatStatus(masterId: string, targetId: string) {
    const ret = await this.chatListCard
      .filter((item) => {
        return item.targetId === targetId && item.masterId === masterId;
      })
      .first();

    return ret?.inChat;
  }
}
