1
0
Fork 0
pdsman-ios/PDSMan/ViewModels/PDSViewModel.swift
2025-03-19 01:55:58 -06:00

99 lines
No EOL
2.7 KiB
Swift

import Foundation
import SwiftUI
import Combine
@MainActor
class PDSViewModel: ObservableObject {
@Published var pdsService = PDSService()
@Published var alertItem: AlertItem?
var errorMessage: String? {
pdsService.errorMessage
}
var isLoading: Bool {
pdsService.isLoading
}
var isAuthenticated: Bool {
get {
let value = pdsService.isAuthenticated
print("PDSViewModel: isAuthenticated getter called, value = \(value)")
return value
}
}
var users: [PDSUser] {
pdsService.users
}
var inviteCodes: [InviteCode] {
pdsService.inviteCodes
}
// Add listeners for PDSService changes
init() {
// Subscribe to PDSService objectWillChange events
pdsService.objectWillChange.sink { [weak self] _ in
// Forward the change notification to our own objectWillChange
DispatchQueue.main.async {
self?.objectWillChange.send()
}
}
.store(in: &cancellables)
}
// Storage for cancellables
private var cancellables = Set<AnyCancellable>()
// Method to manually refresh UI data
func refreshUI() {
DispatchQueue.main.async {
self.objectWillChange.send()
}
}
// Refresh invite codes with UI update
func refreshInviteCodes() async {
await pdsService.fetchInviteCodes()
refreshUI()
}
// Refresh users with UI update
func refreshUsers() async {
await pdsService.fetchUsers()
refreshUI()
}
// Disable invite code with guaranteed UI update
func disableInviteCode(_ code: String) async -> Bool {
let result = await pdsService.disableInviteCode(code)
refreshUI()
return result
}
func login(serverURL: String, username: String, password: String) async {
print("PDSViewModel: login called")
if let credentials = PDSCredentials(serverURL: serverURL, username: username, password: password) {
let success = await pdsService.login(credentials: credentials)
print("PDSViewModel: login completed, success = \(success), isAuthenticated = \(pdsService.isAuthenticated)")
// Force update the view by triggering objectWillChange
objectWillChange.send()
} else {
pdsService.errorMessage = "Invalid credentials"
}
}
func logout() {
print("PDSViewModel: logout called")
pdsService.logout()
objectWillChange.send()
}
}
struct AlertItem: Identifiable {
let id = UUID()
let title: String
let message: String
}