yattee/Model/Accounts/InstancesModel.swift

48 lines
1.3 KiB
Swift
Raw Normal View History

2021-09-25 08:18:22 +00:00
import Defaults
import Foundation
final class InstancesModel: ObservableObject {
2021-10-16 22:48:58 +00:00
var all: [Instance] {
Defaults[.instances]
}
var lastUsed: Instance? {
guard let id = Defaults[.lastInstanceID] else {
return nil
2021-09-26 22:03:33 +00:00
}
2021-09-29 10:14:43 +00:00
return InstancesModel.find(id)
2021-09-25 08:18:22 +00:00
}
static func find(_ id: Instance.ID?) -> Instance? {
2021-09-25 08:18:22 +00:00
guard id != nil else {
return nil
}
return Defaults[.instances].first { $0.id == id }
}
2021-10-20 22:21:50 +00:00
static func accounts(_ id: Instance.ID?) -> [Account] {
Defaults[.accounts].filter { $0.instanceID == id }
2021-09-25 08:18:22 +00:00
}
2021-10-20 22:21:50 +00:00
static func add(app: VideosApp, name: String, url: String) -> Instance {
let instance = Instance(app: app, id: UUID().uuidString, name: name, url: url)
2021-09-25 08:18:22 +00:00
Defaults[.instances].append(instance)
return instance
}
static func remove(_ instance: Instance) {
let accounts = InstancesModel.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)
accounts.forEach { AccountsModel.remove($0) }
2021-09-25 08:18:22 +00:00
}
}
2021-09-26 22:03:33 +00:00
2021-10-20 22:21:50 +00:00
static func setLastAccount(_ account: Account?) {
Defaults[.lastAccountID] = account?.id
2021-09-29 10:14:43 +00:00
}
2021-09-25 08:18:22 +00:00
}