2019-09-13 23:12:19 +02:00
|
|
|
//
|
|
|
|
// AccountMetadataFile.swift
|
|
|
|
// Account
|
|
|
|
//
|
|
|
|
// Created by Maurice Parker on 9/13/19.
|
|
|
|
// Copyright © 2019 Ranchero Software, LLC. All rights reserved.
|
|
|
|
//
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
import os.log
|
|
|
|
import RSCore
|
|
|
|
|
|
|
|
final class AccountMetadataFile {
|
|
|
|
|
2019-09-13 23:35:53 +02:00
|
|
|
private var log = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "accountMetadataFile")
|
2019-09-13 23:12:19 +02:00
|
|
|
|
|
|
|
private let fileURL: URL
|
|
|
|
private let account: Account
|
|
|
|
|
2020-02-09 22:08:11 +01:00
|
|
|
private var isDirty = false {
|
|
|
|
didSet {
|
|
|
|
queueSaveToDiskIfNeeded()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
private let saveQueue = CoalescingQueue(name: "Save Queue", interval: 0.5)
|
|
|
|
|
2019-09-13 23:12:19 +02:00
|
|
|
init(filename: String, account: Account) {
|
|
|
|
self.fileURL = URL(fileURLWithPath: filename)
|
|
|
|
self.account = account
|
|
|
|
}
|
|
|
|
|
|
|
|
func markAsDirty() {
|
2020-02-09 22:08:11 +01:00
|
|
|
isDirty = true
|
2019-09-13 23:12:19 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func load() {
|
2020-03-03 20:39:04 +01:00
|
|
|
if let fileData = try? Data(contentsOf: fileURL) {
|
|
|
|
let decoder = PropertyListDecoder()
|
|
|
|
account.metadata = (try? decoder.decode(AccountMetadata.self, from: fileData)) ?? AccountMetadata()
|
2019-09-13 23:12:19 +02:00
|
|
|
}
|
2020-03-03 20:39:04 +01:00
|
|
|
account.metadata.delegate = account
|
2019-09-13 23:12:19 +02:00
|
|
|
}
|
|
|
|
|
2020-02-09 22:08:11 +01:00
|
|
|
func save() {
|
2019-09-13 23:12:19 +02:00
|
|
|
guard !account.isDeleted else { return }
|
|
|
|
|
|
|
|
let encoder = PropertyListEncoder()
|
|
|
|
encoder.outputFormat = .binary
|
|
|
|
|
2020-03-03 20:39:04 +01:00
|
|
|
do {
|
|
|
|
let data = try encoder.encode(account.metadata)
|
|
|
|
try data.write(to: fileURL)
|
|
|
|
} catch let error as NSError {
|
|
|
|
os_log(.error, log: log, "Save to disk failed: %@.", error.localizedDescription)
|
2019-09-13 23:12:19 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
2020-02-09 22:08:11 +01:00
|
|
|
|
|
|
|
private extension AccountMetadataFile {
|
|
|
|
|
|
|
|
func queueSaveToDiskIfNeeded() {
|
|
|
|
saveQueue.add(self, #selector(saveToDiskIfNeeded))
|
|
|
|
}
|
|
|
|
|
|
|
|
@objc func saveToDiskIfNeeded() {
|
|
|
|
if isDirty {
|
|
|
|
isDirty = false
|
|
|
|
save()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|