import Foundation import GRDB import Martin final class ClientMartinChatsManager: Martin.ChatManager { func chats(for context: Martin.Context) -> [any Martin.ChatProtocol] { do { let chats: [Chat] = try Database.shared.dbQueue.read { db in try Chat.filter(Column("account") == context.userBareJid.stringValue).fetchAll(db) } return chats.map { chat in Martin.ChatBase(context: context, jid: BareJID(chat.participant)) } } catch { logIt(.error, "Error fetching chats: \(error.localizedDescription)") return [] } } func chat(for context: Martin.Context, with: Martin.BareJID) -> (any Martin.ChatProtocol)? { do { let chat: Chat? = try Database.shared.dbQueue.read { db in try Chat .filter(Column("account") == context.userBareJid.stringValue) .filter(Column("participant") == with.stringValue) .fetchOne(db) } if chat != nil { return Martin.ChatBase(context: context, jid: with) } else { return nil } } catch { logIt(.error, "Error fetching chat: \(error.localizedDescription)") return nil } } func createChat(for context: Martin.Context, with: Martin.BareJID) -> (any Martin.ChatProtocol)? { do { let chat: Chat? = try Database.shared.dbQueue.read { db in try Chat .filter(Column("account") == context.userBareJid.stringValue) .filter(Column("participant") == with.stringValue) .fetchOne(db) } if chat != nil { return Martin.ChatBase(context: context, jid: with) } else { let chat = Chat( id: UUID().uuidString, account: context.userBareJid.stringValue, participant: with.stringValue, type: .chat ) try Database.shared.dbQueue.write { db in try chat.save(db) } return Martin.ChatBase(context: context, jid: with) } } catch { logIt(.error, "Error fetching chat: \(error.localizedDescription)") return nil } } func close(chat: any Martin.ChatProtocol) -> Bool { // not used in Martin library for now print("Closing chat: \(chat)") return false } func initialize(context _: Martin.Context) {} func deinitialize(context _: Martin.Context) {} }