//
//  TSDBAIChatList.swift
//  AIEmoji
//
//  Created by 100Years on 2025/2/10.
//

import RealmSwift
import MessageKit

//MARK: TSDBAIChatList - 用于存储会话及消息列表
class TSDBAIChatList: Object {
    @objc dynamic var sessionId = UUID().uuidString
    dynamic var messages = List<TSDBChatMessage>()
    @objc dynamic var creatTimestampInt:Int = 0
    
    
    
//    var messageList: [TSChatMessage] = []
    
    override static func primaryKey() -> String? {
        return "sessionId"
    }

//    //获取 App 层的 最新的 TSChatMessage 数组
//    func getMessageListLatestData() {
//        messageList = getMessageList()
//    }
    
    //获取 App 层的 TSChatMessage 数组
    func getMessageList() -> [TSChatMessage] {
        var msgModel:[TSChatMessage] = []
        for msgDBModel in messages {
            msgModel.append(msgDBModel.getTSChatMessage())
        }
        return msgModel
    }
    
//    //添加 App 层的 TSChatMessage 数组
//    func updateMessageList(list:[TSChatMessage]){
//        TSRMShared.writeThread {
//            if creatTimestampInt == 0 {
//                creatTimestampInt = Date.timestampInt
//            }
//            messages.removeAll()
//            for model in list {
//                messages.append(getTSDBChatMessage(chatMsg: model))
//            }
//        }
//        TSRMShared.update(self)
//    }
    
    func delete() {
        TSRMShared.delete(self)
    }
    
    
    func updateMessage(msgModel:TSChatMessage){
        TSRMShared.writeThread {
            if creatTimestampInt == 0 {
                creatTimestampInt = Date.timestampInt
            }
            let dbModel = getTSDBChatMessage(chatMsg: msgModel)
            if let index = messages.firstIndex(where: { $0.messageId == dbModel.messageId }) {
                messages[index] = dbModel// 如果找到，替换该元素
            } else {
                messages.append(dbModel)// 如果没有找到，添加到末尾
            }
        }
        TSRMShared.update(self)
    }
    
    
    func updateMessages(msgModels:[TSChatMessage]){
        TSRMShared.writeThread {
            if creatTimestampInt == 0 {
                creatTimestampInt = Date.timestampInt
            }
            for msgModel in msgModels {
                let dbModel = getTSDBChatMessage(chatMsg: msgModel)
                if let index = messages.firstIndex(where: { $0.messageId == dbModel.messageId }) {
                    messages[index] = dbModel// 如果找到，替换该元素
                } else {
                    messages.append(dbModel)// 如果没有找到，添加到末尾
                }
            }
        }
        TSRMShared.update(self)
    }
    
}


extension TSDBAIChatList {
    
    static func getOneDB() -> TSDBAIChatList{
        let dbModel = TSDBAIChatList()
//        TSRMShared.create(dbModel)
        return dbModel
    }
    
    //获取所有储存的 TSDBAIChatList
    static func getAll() -> [TSDBAIChatList] {
        var list:[TSDBAIChatList] = []
        let allPersons = TSRMShared.read(TSDBAIChatList.self)
        for person in allPersons {
            list.append(person)
        }
        return list
    }
}

extension TSDBAIChatList {
    
    func getTSDBChatMessage(chatMsg:TSChatMessage) -> TSDBChatMessage {
        let dbModel = TSDBChatMessage()
        dbModel.messageId = chatMsg.messageId
        dbModel.sentDate = chatMsg.sentDate
        dbModel.kind = chatMsg.kind.kindString
        dbModel.user = TSDBChatUser(senderId: chatMsg.user.senderId, displayName: chatMsg.user.displayName)
        dbModel.messageId = chatMsg.messageId
        
        return dbModel
    }
    
}


//MARK: extension
extension MessageKind {
    static func fromString(_ string: String) -> MessageKind {
        if string == "text" {
            return .text("")
        } else if string == "attributedText" {
            return .attributedText(NSAttributedString())
        } else if string == "emoji" {
            return .emoji("")
        } else {
            return .custom(nil)
        }
    }
    
    
    var kindString:String{
        switch self {
            case .text(let text), .emoji(let text): return text
            default: return ""
        }
    }
    
    
    static func textKind(_ string: String) -> MessageKind {
        return .text(string)
    }
    
}


// TSChatMessage - 用于存储聊天消息
class TSDBChatMessage: Object {
    @objc dynamic var messageId: String = UUID().uuidString
    @objc dynamic var sentDate: Date = Date()
    @objc dynamic var kind: String = ""
    @objc dynamic var user: TSDBChatUser? = TSDBChatUser(senderId: "", displayName: "")

    override static func primaryKey() -> String? {
        return "messageId"
    }
    
    func getTSChatMessage() -> TSChatMessage {
        let model = TSChatMessage(kind: .textKind(kind), user: user!.getTSChatUser(), messageId: messageId, date: sentDate)
        return model
    }
    
    override init() {
        super.init()
    }
    
}

class TSDBChatUser: Object {
    @objc dynamic var senderId: String = ""
    @objc dynamic var displayName: String = ""
    
    func getTSChatUser() -> TSChatUser {
        let user = TSChatUser(senderId: senderId, displayName: displayName)
        return user
    }
    
    init(senderId: String, displayName: String) {
        self.senderId = senderId
        self.displayName = displayName
    }
    
    override init() {
        super.init()
    }
}



