2024-08-14 13:48:30 +00:00
|
|
|
import Collections
|
|
|
|
import Combine
|
2024-08-13 08:40:27 +00:00
|
|
|
import Foundation
|
2024-08-14 13:48:30 +00:00
|
|
|
import GRDB
|
2024-08-13 08:40:27 +00:00
|
|
|
|
|
|
|
@MainActor
|
|
|
|
final class ConversationStore: ObservableObject {
|
2024-08-14 13:48:30 +00:00
|
|
|
@Published private(set) var messages: Deque<Message> = []
|
|
|
|
private(set) var roster: Roster
|
2024-08-13 08:40:27 +00:00
|
|
|
|
|
|
|
private let client: Client
|
2024-08-14 13:48:30 +00:00
|
|
|
private let blockSize = Const.messagesPageSize
|
|
|
|
private let messagesMax = Const.messagesMaxSize
|
|
|
|
|
|
|
|
private var messagesObservation: AnyDatabaseCancellable
|
2024-08-13 08:40:27 +00:00
|
|
|
|
|
|
|
init(roster: Roster, client: Client) {
|
|
|
|
self.client = client
|
|
|
|
self.roster = roster
|
2024-08-14 13:48:30 +00:00
|
|
|
|
|
|
|
// observe change messages in database
|
|
|
|
messagesObservation = DatabaseRegionObservation(tracking: Message.all()).start(in: Database.shared.dbQueue) { _ in
|
|
|
|
// Handle error
|
|
|
|
} onChange: { _ in
|
|
|
|
print("Messages were changed")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
extension ConversationStore {
|
|
|
|
func loadMoreBackward() async {
|
|
|
|
// guard let lastMessage = messages.last else { return }
|
|
|
|
// let messages = await fetchBlock(lastMessage.date, nil)
|
|
|
|
// self.messages.append(contentsOf: messages)
|
|
|
|
}
|
|
|
|
|
|
|
|
func loadMoreForward() async {
|
|
|
|
// guard let firstMessage = messages.first else { return }
|
|
|
|
// let messages = await fetchBlock(nil, firstMessage.date)
|
|
|
|
// self.messages.insert(contentsOf: messages, at: 0)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
extension ConversationStore {
|
|
|
|
private func fetchBlock(_ beforeDate: Date?, _ afterDate: Date?) async -> [Message] {
|
|
|
|
print(beforeDate, afterDate)
|
|
|
|
return []
|
|
|
|
// let messages = await client.fetchMessages()
|
|
|
|
// self.messages.append(contentsOf: messages)
|
|
|
|
}
|
|
|
|
|
|
|
|
private func cutMessages() {
|
|
|
|
// if messages.count > messagesMax {
|
|
|
|
// messages.removeFirst(messages.count - messagesMax)
|
|
|
|
// }
|
2024-08-13 08:40:27 +00:00
|
|
|
}
|
|
|
|
}
|