//
//  YHAIChatDataBaseManager.swift
//  galaxy
//
//  Created by Dufet on 2024/12/2.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import Realm
import RealmSwift

class YHAIChatDataBaseManager {
    
    static let shared = YHAIChatDataBaseManager()
    let dbName = "AI_CHAT_DB.realm"
    // 如果要存储的数据模型属性发生变化,需要配置当前版本号比之前大
    let dbVersion: UInt64 = 1
    
    init() {
        configDataBase()
    }
    
    private func configDataBase() {
        let docPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as String
        let dbPath = docPath.appending("/\(dbName)")
        let config = Realm.Configuration(fileURL: URL.init(string: dbPath), inMemoryIdentifier: nil, encryptionKey: nil, readOnly: false, schemaVersion: dbVersion, migrationBlock: { (migration, oldSchemaVersion) in
            
        }, deleteRealmIfMigrationNeeded: false, shouldCompactOnLaunch: nil, objectTypes: nil)
        Realm.Configuration.defaultConfiguration = config
        Realm.asyncOpen { result in
            switch result {
            case let .success(succeed):
                print("Realm 服务器配置成功!")
                break
            case let .failure(error):
                print("Realm 数据库配置失败：\(error.localizedDescription)")
                break
            }
        }
    }
    
    private func getDB() -> Realm {
        let docPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as String
        let dbPath = docPath.appending("/\(dbName)")
        /// 传入路径会自动创建数据库
        let defaultRealm = try! Realm(fileURL: URL.init(string: dbPath)!)
        return defaultRealm
    }
    
    func addDBMessages(_ messages: [YHAIChatDBMessage]) {
        // 获取 Realm 实例
        let defaultRealm = self.getDB()
        // 开始写入事务
        for message in messages {
            let students = getDBMessageBy(uuid: message.uuid)
            try! defaultRealm.write {
                // 将新对象添加到 Realm 数据库
                defaultRealm.add(message, update: students.count > 0 ? .modified : .all)
            }
        }
    }
    
    func addDBMessage(_ message: YHAIChatDBMessage) -> Void {
        let defaultRealm = self.getDB()
        try! defaultRealm.write {
            defaultRealm.add(message)
        }
        print(defaultRealm.configuration.fileURL ?? "")
    }
    
    /// 获取 所保存的消息
    func getDBMessages() -> Results<YHAIChatDBMessage> {
        let defaultRealm = self.getDB()
        return defaultRealm.objects(YHAIChatDBMessage.self)
    }
    
    func  getDBMessageBy(uuid: String) -> Results<YHAIChatDBMessage> {
        return self.readDBMessages("uuid = '\(uuid)'")
    }
    
    func readDBMessages(_ predicate: String) -> Results<YHAIChatDBMessage> {
        let defaultRealm = self.getDB()
        print(defaultRealm.configuration.fileURL ?? "")
        let predicate = NSPredicate(format: predicate)
        let results = defaultRealm.objects(YHAIChatDBMessage.self)
        return  results.filter(predicate)
    }
    
    func readHistoryUIMessages() -> [YHAIChatMessage] {
        let result = YHAIChatDataBaseManager.shared.getDBMessages()
        var arr = [YHAIChatMessage]()
        for msg in result {
            let model = msg.getMessage()
            arr.append(model)
        }
        return arr
    }
}

