2021-09-25 13:48:22 +05:30
|
|
|
import Defaults
|
|
|
|
import Foundation
|
|
|
|
|
|
|
|
final class InstancesModel: ObservableObject {
|
2021-10-17 04:18:58 +05:30
|
|
|
var all: [Instance] {
|
|
|
|
Defaults[.instances]
|
|
|
|
}
|
|
|
|
|
2021-10-20 02:57:04 +05:30
|
|
|
var lastUsed: Instance? {
|
|
|
|
guard let id = Defaults[.lastInstanceID] else {
|
|
|
|
return nil
|
2021-09-27 03:33:33 +05:30
|
|
|
}
|
2021-09-29 15:44:43 +05:30
|
|
|
|
2021-10-20 02:57:04 +05:30
|
|
|
return InstancesModel.find(id)
|
2021-09-25 13:48:22 +05:30
|
|
|
}
|
|
|
|
|
2021-10-20 02:57:04 +05:30
|
|
|
static func find(_ id: Instance.ID?) -> Instance? {
|
2021-09-25 13:48:22 +05:30
|
|
|
guard id != nil else {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return Defaults[.instances].first { $0.id == id }
|
|
|
|
}
|
|
|
|
|
2021-10-20 02:57:04 +05:30
|
|
|
static func accounts(_ id: Instance.ID?) -> [Instance.Account] {
|
2021-09-27 02:09:27 +05:30
|
|
|
Defaults[.accounts].filter { $0.instanceID == id }
|
2021-09-25 13:48:22 +05:30
|
|
|
}
|
|
|
|
|
2021-10-20 02:57:04 +05:30
|
|
|
static func add(app: Instance.App, name: String, url: String) -> Instance {
|
|
|
|
let instance = Instance(app: app, id: UUID().uuidString, name: name, url: url)
|
2021-09-25 13:48:22 +05:30
|
|
|
Defaults[.instances].append(instance)
|
|
|
|
|
|
|
|
return instance
|
|
|
|
}
|
|
|
|
|
2021-10-20 02:57:04 +05:30
|
|
|
static func remove(_ instance: Instance) {
|
|
|
|
let accounts = InstancesModel.accounts(instance.id)
|
2021-09-25 13:48:22 +05:30
|
|
|
if let index = Defaults[.instances].firstIndex(where: { $0.id == instance.id }) {
|
|
|
|
Defaults[.instances].remove(at: index)
|
2021-10-20 02:57:04 +05:30
|
|
|
accounts.forEach { AccountsModel.remove($0) }
|
2021-09-25 13:48:22 +05:30
|
|
|
}
|
|
|
|
}
|
2021-09-27 03:33:33 +05:30
|
|
|
|
2021-10-20 02:57:04 +05:30
|
|
|
static func setLastAccount(_ account: Instance.Account?) {
|
|
|
|
Defaults[.lastAccountID] = account?.id
|
2021-09-29 15:44:43 +05:30
|
|
|
}
|
2021-09-25 13:48:22 +05:30
|
|
|
}
|