IceCubes/IceCubesApp/App/AppAccounts/AppAccountsManager.swift

50 lines
1.6 KiB
Swift
Raw Normal View History

2022-12-01 09:05:26 +01:00
import SwiftUI
import Network
class AppAccountsManager: ObservableObject {
2022-12-30 08:36:22 +01:00
@AppStorage("latestCurrentAccountKey") static public var latestCurrentAccountKey: String = ""
2022-12-01 09:05:26 +01:00
@Published var currentAccount: AppAccount {
didSet {
2022-12-30 08:36:22 +01:00
Self.latestCurrentAccountKey = currentAccount.id
2022-12-01 09:05:26 +01:00
currentClient = .init(server: currentAccount.server,
oauthToken: currentAccount.oauthToken)
}
}
2022-12-29 07:00:00 +01:00
@Published var availableAccounts: [AppAccount]
2022-12-01 09:05:26 +01:00
@Published var currentClient: Client
init() {
var defaultAccount = AppAccount(server: IceCubesApp.defaultServer, oauthToken: nil)
do {
let keychainAccounts = try AppAccount.retrieveAll()
2022-12-29 07:00:00 +01:00
availableAccounts = keychainAccounts
2022-12-30 08:36:22 +01:00
if let currentAccount = keychainAccounts.first(where: { $0.id == Self.latestCurrentAccountKey }) {
defaultAccount = currentAccount
} else {
defaultAccount = keychainAccounts.last ?? defaultAccount
}
} catch {
availableAccounts = [defaultAccount]
}
2022-12-01 09:05:26 +01:00
currentAccount = defaultAccount
currentClient = .init(server: defaultAccount.server, oauthToken: defaultAccount.oauthToken)
}
func add(account: AppAccount) {
do {
try account.save()
2022-12-30 08:36:22 +01:00
availableAccounts.append(account)
2022-12-30 08:58:32 +01:00
currentAccount = account
2022-12-01 09:05:26 +01:00
} catch { }
}
func delete(account: AppAccount) {
2022-12-30 08:36:22 +01:00
availableAccounts.removeAll(where: { $0.id == account.id })
2022-12-01 09:05:26 +01:00
account.delete()
2022-12-30 08:36:22 +01:00
if currentAccount.id == account.id {
currentAccount = availableAccounts.first ?? AppAccount(server: IceCubesApp.defaultServer, oauthToken: nil)
}
2022-12-01 09:05:26 +01:00
}
}