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

import RealmSwift
import MessageKit

//MARK: TSDBAIChatList - 用于存储会话及消息列表
class TSDBAIChatList: Object {
    override static func primaryKey() -> String? {
        return "sessionId"
    }
    @objc dynamic var sessionId = UUID().uuidString
    dynamic var messages = List<TSDBChatMessage>()
    @objc dynamic var creatTimestampInt:Int = 0
    
    //获取 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)
    }
    
    static func deleteAll() {
        do {
            let realm = try Realm()
            // 开始写入事务
            try realm.write {
                // 查询 Person 模型的所有对象
                let allPersons = realm.objects(TSDBAIChatList.self)
                // 删除所有查询到的对象
                realm.delete(allPersons)
            }
            print("Person 模型的所有数据删除成功")
        } catch {
            print("删除 Person 模型数据时出错: \(error)")
        }
    }
    
    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()
        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 keyValue = chatMsg.kind.keyValue
        
        let dbModel = TSDBChatMessage()
        dbModel.user = TSDBChatUser(senderId: chatMsg.user.senderId, displayName: chatMsg.user.displayName)
        dbModel.messageId = chatMsg.messageId
        dbModel.sentDate = chatMsg.sentDate
        dbModel.kindKey = keyValue.0
        dbModel.kindValue = keyValue.1
        return dbModel
    }
    
}


//MARK: extension
extension MessageKind {

    static func fromKeyValue(key string: String,value:String) -> MessageKind {
        if string == "text" {
            return .text(value)
        } else if string == "attributedText" {
            return .attributedText(kMDAttributedString(text: value))
        } else {
            return .custom(nil)
        }
    }
    
    var keyValue:(String,String){
        switch self {
        case .text(let text):
            return ("text",text)
        case .attributedText(let attributedString):
            return ("attributedText",attributedString.string)
        default:
            return ("default","")
        }
    }
    
    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 user: TSDBChatUser? = TSDBChatUser(senderId: "", displayName: "")
    @objc dynamic var kindKey: String = ""
    @objc dynamic var kindValue: String = ""
    
    override static func primaryKey() -> String? {
        return "messageId"
    }
    
    func getTSChatMessage() -> TSChatMessage {
        let model = TSChatMessage(kind: .fromKeyValue(key: kindKey, value: kindValue), 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()
    }
}



