import { DisplayMessage } from '@/store/messagesStore'
import {
  getMasterIdFromDisplayMsg,
  getTargetIdFromDisplayMsg,
} from '@/utils/chatutils'
import ChatListCardDB from './ChatListCardDB'
import ChatMessageDB from './ChatMessageDB'

interface iRecevedMsg {
  msg: DisplayMessage
  masterId: string
  isChattingWithTargetId: boolean
  isRoboot?: boolean
}

export default class ChatDBService {
  static instance: ChatDBService
  static getInstance() {
    if (!ChatDBService.instance) ChatDBService.instance = new ChatDBService()
    return ChatDBService.instance
  }

  async handleEveryReceive(data: {
    msg: DisplayMessage
    masterId: string
    isChattingWithTargetId: boolean
    isRoboot?: boolean
  }) {
    let firstInsert = false
    const isQueueEmpty = this.dataList.length === 0
    if (isQueueEmpty) {
      firstInsert = true
    }
    this.pushToList(data)
    if (firstInsert === true) {
      await this.exec(this.dataList[0])
      this.dataList.shift()
      this.startExecList()
    }
  }

  private async startExecList(): Promise<any> {
    if (this.dataList.length !== 0) {
      const msg = this.dataList[0]
      await this.exec(msg)
      this.dataList.shift()
      return this.startExecList()
    }
  }

  private async exec(data: {
    msg: DisplayMessage
    masterId: string
    isChattingWithTargetId: boolean
    isRoboot?: boolean
  }) {
    /* 检查和对象之间的聊天记录，如果数量为0，则表示之前没有和他聊过，需要新增一个chatcard */
    /* 如果数量为1，表示之前和他聊过 */
    const { msg, masterId, isChattingWithTargetId } = data

    const thePersonAlreadyInChatList = await ChatMessageDB.getInstance().thePersonAlreadyInChatList(
      getMasterIdFromDisplayMsg(msg),
      getTargetIdFromDisplayMsg(msg),
    )
    await ChatMessageDB.getInstance().saveMsg(msg, masterId)
    if (thePersonAlreadyInChatList) {
      return await ChatListCardDB.getInstance().updateNewestCard({
        msg,
        isChattingWithTargetId,
      })
    } else {
      return await ChatListCardDB.getInstance().addNewCard({
        msg,
        isChattingWithTargetId,
        isRobootCard: data.isRoboot,
      })
    }
  }

  private dataList = [] as iRecevedMsg[]

  private pushToList(msg: iRecevedMsg) {
    this.dataList.push(msg)
  }
}
