yattee/Model/InstancesModel.swift

72 lines
2.0 KiB
Swift
Raw Normal View History

2021-09-25 08:18:22 +00:00
import Defaults
import Foundation
final class InstancesModel: ObservableObject {
2021-09-26 22:03:33 +00:00
@Published var defaultAccount: Instance.Account?
2021-10-16 22:48:58 +00:00
var all: [Instance] {
Defaults[.instances]
}
2021-09-26 22:03:33 +00:00
init() {
2021-10-16 22:48:58 +00:00
guard let id = Defaults[.defaultAccountID] else {
2021-09-29 10:14:43 +00:00
return
2021-09-26 22:03:33 +00:00
}
2021-09-29 10:14:43 +00:00
2021-10-16 22:48:58 +00:00
defaultAccount = findAccount(id)
2021-09-25 08:18:22 +00:00
}
func find(_ id: Instance.ID?) -> Instance? {
guard id != nil else {
return nil
}
return Defaults[.instances].first { $0.id == id }
}
func accounts(_ id: Instance.ID?) -> [Instance.Account] {
Defaults[.accounts].filter { $0.instanceID == id }
2021-09-25 08:18:22 +00:00
}
2021-10-16 22:48:58 +00:00
func add(app: Instance.App, name: String, url: String) -> Instance {
let instance = Instance(app: app, name: name, url: url)
2021-09-25 08:18:22 +00:00
Defaults[.instances].append(instance)
return instance
}
func remove(_ instance: Instance) {
2021-09-26 22:03:33 +00:00
let accounts = accounts(instance.id)
2021-09-25 08:18:22 +00:00
if let index = Defaults[.instances].firstIndex(where: { $0.id == instance.id }) {
Defaults[.instances].remove(at: index)
2021-09-26 22:03:33 +00:00
accounts.forEach { removeAccount($0) }
2021-09-25 08:18:22 +00:00
}
}
2021-09-29 10:14:43 +00:00
func findAccount(_ id: Instance.Account.ID) -> Instance.Account? {
Defaults[.accounts].first { $0.id == id }
}
2021-09-25 08:18:22 +00:00
func addAccount(instance: Instance, name: String, sid: String) -> Instance.Account {
let account = Instance.Account(instanceID: instance.id, name: name, url: instance.url, sid: sid)
Defaults[.accounts].append(account)
2021-09-25 08:18:22 +00:00
return account
}
func removeAccount(_ account: Instance.Account) {
if let accountIndex = Defaults[.accounts].firstIndex(where: { $0.id == account.id }) {
Defaults[.accounts].remove(at: accountIndex)
2021-09-25 08:18:22 +00:00
}
}
2021-09-26 22:03:33 +00:00
func setDefaultAccount(_ account: Instance.Account?) {
2021-10-16 22:48:58 +00:00
Defaults[.defaultAccountID] = account?.id
2021-09-26 22:03:33 +00:00
defaultAccount = account
}
2021-09-29 10:14:43 +00:00
func resetDefaultAccount() {
setDefaultAccount(nil)
}
2021-09-25 08:18:22 +00:00
}