IceCubesApp/Packages/Account/Sources/Account/AccountDetailViewModel.swift

67 lines
1.8 KiB
Swift
Raw Normal View History

2022-11-29 11:18:06 +00:00
import SwiftUI
import Network
import Models
2022-12-19 06:17:01 +00:00
import Status
2022-11-29 11:18:06 +00:00
@MainActor
2022-12-19 06:17:01 +00:00
class AccountDetailViewModel: ObservableObject, StatusesFetcher {
2022-11-29 11:18:06 +00:00
let accountId: String
2022-12-19 11:28:55 +00:00
var client: Client?
2022-11-29 11:18:06 +00:00
enum State {
2022-12-01 08:05:26 +00:00
case loading, data(account: Account), error(error: Error)
2022-11-29 11:18:06 +00:00
}
2022-12-19 06:17:01 +00:00
2022-12-18 19:30:19 +00:00
2022-11-29 11:18:06 +00:00
@Published var state: State = .loading
2022-12-18 19:30:19 +00:00
@Published var statusesState: StatusesState = .loading
2022-12-20 08:37:07 +00:00
@Published var title: String = ""
2022-12-18 19:30:19 +00:00
2022-12-20 08:37:07 +00:00
private var account: Account?
2022-12-18 19:30:19 +00:00
private var statuses: [Status] = []
2022-11-29 11:18:06 +00:00
init(accountId: String) {
self.accountId = accountId
}
2022-12-17 12:37:46 +00:00
init(account: Account) {
self.accountId = account.id
self.state = .data(account: account)
}
2022-11-29 11:18:06 +00:00
func fetchAccount() async {
2022-12-19 11:28:55 +00:00
guard let client else { return }
2022-11-29 11:18:06 +00:00
do {
2022-12-20 08:37:07 +00:00
let account: Account = try await client.get(endpoint: Accounts.accounts(id: accountId))
self.title = account.displayName
state = .data(account: account)
2022-11-29 11:18:06 +00:00
} catch {
state = .error(error: error)
}
}
2022-12-18 19:30:19 +00:00
func fetchStatuses() async {
2022-12-19 11:28:55 +00:00
guard let client else { return }
2022-12-18 19:30:19 +00:00
do {
statusesState = .loading
statuses = try await client.get(endpoint: Accounts.statuses(id: accountId, sinceId: nil))
statusesState = .display(statuses: statuses, nextPageState: .hasNextPage)
} catch {
statusesState = .error(error: error)
}
}
2022-12-19 06:17:01 +00:00
func fetchNextPage() async {
2022-12-19 11:28:55 +00:00
guard let client else { return }
2022-12-18 19:30:19 +00:00
do {
guard let lastId = statuses.last?.id else { return }
statusesState = .display(statuses: statuses, nextPageState: .loadingNextPage)
let newStatuses: [Status] = try await client.get(endpoint: Accounts.statuses(id: accountId, sinceId: lastId))
statuses.append(contentsOf: newStatuses)
statusesState = .display(statuses: statuses, nextPageState: .hasNextPage)
} catch {
statusesState = .error(error: error)
}
}
2022-11-29 11:18:06 +00:00
}