2022-04-11 16:29:19 +02:00
|
|
|
//
|
|
|
|
// Database.swift
|
|
|
|
// App
|
|
|
|
//
|
|
|
|
// Created by Rasmus Krämer on 11.04.22.
|
|
|
|
//
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
import RealmSwift
|
|
|
|
|
|
|
|
class Database {
|
|
|
|
public static let realmQueue = DispatchQueue(label: "realm-queue")
|
2022-04-11 18:50:25 +02:00
|
|
|
|
|
|
|
// All DB releated actions must be executed on "realm-queue"
|
|
|
|
private static var instance: Realm = {
|
|
|
|
// TODO: handle thread errors
|
|
|
|
try! Realm(queue: realmQueue)
|
|
|
|
}()
|
|
|
|
|
2022-04-11 18:31:14 +02:00
|
|
|
public static func getActiveServerConfigIndex() -> Int {
|
2022-04-14 11:54:53 +02:00
|
|
|
return realmQueue.sync {
|
|
|
|
guard let config = instance.objects(ServerConnectionConfig.self).first else {
|
|
|
|
return -1
|
|
|
|
}
|
|
|
|
return config.index
|
2022-04-11 18:31:14 +02:00
|
|
|
}
|
|
|
|
}
|
2022-04-11 16:29:19 +02:00
|
|
|
|
|
|
|
public static func setServerConnectionConfig(config: ServerConnectionConfig) {
|
2022-04-14 11:54:53 +02:00
|
|
|
var refrence: ThreadSafeReference<ServerConnectionConfig>?
|
|
|
|
if config.realm != nil {
|
|
|
|
refrence = ThreadSafeReference(to: config)
|
|
|
|
}
|
2022-04-11 16:29:19 +02:00
|
|
|
|
2022-04-14 11:54:53 +02:00
|
|
|
realmQueue.sync {
|
|
|
|
let existing: ServerConnectionConfig? = instance.object(ofType: ServerConnectionConfig.self, forPrimaryKey: config.id)
|
|
|
|
|
|
|
|
do {
|
|
|
|
try instance.write {
|
|
|
|
if existing != nil {
|
|
|
|
instance.delete(existing!)
|
|
|
|
}
|
|
|
|
if refrence == nil {
|
|
|
|
instance.add(config)
|
|
|
|
} else {
|
|
|
|
guard let resolved = instance.resolve(refrence!) else {
|
|
|
|
throw "unable to resolve refrence"
|
|
|
|
}
|
|
|
|
|
|
|
|
instance.add(resolved);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} catch(let exception) {
|
|
|
|
NSLog("failed to save server config")
|
|
|
|
debugPrint(exception)
|
2022-04-11 18:31:14 +02:00
|
|
|
}
|
2022-04-11 16:29:19 +02:00
|
|
|
}
|
|
|
|
}
|
2022-04-11 18:31:14 +02:00
|
|
|
public static func getServerConnectionConfigs() -> [ServerConnectionConfig] {
|
2022-04-14 11:54:53 +02:00
|
|
|
var refrences: [ThreadSafeReference<ServerConnectionConfig>] = []
|
2022-04-11 16:29:19 +02:00
|
|
|
|
2022-04-14 11:54:53 +02:00
|
|
|
realmQueue.sync {
|
|
|
|
let configs = instance.objects(ServerConnectionConfig.self)
|
|
|
|
refrences = configs.map { config in
|
|
|
|
return ThreadSafeReference(to: config)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
do {
|
|
|
|
let realm = try Realm()
|
|
|
|
|
|
|
|
return refrences.map { refrence in
|
|
|
|
return realm.resolve(refrence)!
|
|
|
|
}
|
|
|
|
} catch(let exception) {
|
|
|
|
NSLog("error while readling configs")
|
|
|
|
debugPrint(exception)
|
2022-04-11 18:31:14 +02:00
|
|
|
return []
|
|
|
|
}
|
2022-04-11 16:29:19 +02:00
|
|
|
}
|
|
|
|
}
|