2023-02-27 05:39:07 +00:00
|
|
|
import Combine
|
2022-12-28 09:08:41 +00:00
|
|
|
import Models
|
2023-01-17 10:36:01 +00:00
|
|
|
import Network
|
|
|
|
import SwiftUI
|
2022-12-28 09:08:41 +00:00
|
|
|
|
|
|
|
@MainActor
|
|
|
|
public class StatusPollViewModel: ObservableObject {
|
|
|
|
public var client: Client?
|
|
|
|
public var instance: Instance?
|
2023-01-17 10:36:01 +00:00
|
|
|
|
2022-12-28 09:08:41 +00:00
|
|
|
@Published var poll: Poll
|
|
|
|
@Published var votes: [Int] = []
|
2023-01-17 10:36:01 +00:00
|
|
|
|
2022-12-28 09:08:41 +00:00
|
|
|
var showResults: Bool {
|
2023-02-09 05:35:19 +00:00
|
|
|
poll.ownVotes?.isEmpty == false || poll.expired
|
2022-12-28 09:08:41 +00:00
|
|
|
}
|
2023-01-17 10:36:01 +00:00
|
|
|
|
2022-12-28 09:08:41 +00:00
|
|
|
public init(poll: Poll) {
|
|
|
|
self.poll = poll
|
2023-01-17 10:36:01 +00:00
|
|
|
votes = poll.ownVotes ?? []
|
2022-12-28 09:08:41 +00:00
|
|
|
}
|
2023-01-17 10:36:01 +00:00
|
|
|
|
2022-12-28 09:08:41 +00:00
|
|
|
public func fetchPoll() async {
|
|
|
|
guard let client else { return }
|
|
|
|
do {
|
|
|
|
poll = try await client.get(endpoint: Polls.poll(id: poll.id))
|
2023-01-03 14:51:36 +00:00
|
|
|
votes = poll.ownVotes ?? []
|
2023-01-17 10:36:01 +00:00
|
|
|
} catch {}
|
2022-12-28 09:08:41 +00:00
|
|
|
}
|
2023-01-17 10:36:01 +00:00
|
|
|
|
2022-12-28 09:08:41 +00:00
|
|
|
public func postVotes() async {
|
|
|
|
guard let client, !poll.expired else { return }
|
|
|
|
do {
|
|
|
|
poll = try await client.post(endpoint: Polls.vote(id: poll.id, votes: votes))
|
|
|
|
withAnimation {
|
2023-01-03 14:51:36 +00:00
|
|
|
votes = poll.ownVotes ?? []
|
2022-12-28 09:08:41 +00:00
|
|
|
}
|
|
|
|
} catch {
|
|
|
|
print(error)
|
|
|
|
}
|
|
|
|
}
|
2023-02-12 15:29:41 +00:00
|
|
|
|
2023-02-09 05:35:19 +00:00
|
|
|
public func handleSelection(_ pollIndex: Int) {
|
|
|
|
if poll.multiple {
|
|
|
|
if let voterIndex = votes.firstIndex(of: pollIndex) {
|
|
|
|
votes.remove(at: voterIndex)
|
|
|
|
} else {
|
|
|
|
votes.append(pollIndex)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
votes = [pollIndex]
|
|
|
|
}
|
|
|
|
}
|
2022-12-28 09:08:41 +00:00
|
|
|
}
|