78 lines
2.4 KiB
Swift
78 lines
2.4 KiB
Swift
//
|
|
// DraftsManager.swift
|
|
// Tusker
|
|
//
|
|
// Created by Shadowfacts on 10/22/18.
|
|
// Copyright © 2018 Shadowfacts. All rights reserved.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
class DraftsManager: Codable, ObservableObject {
|
|
|
|
private(set) static var shared: DraftsManager = load()
|
|
|
|
private static var documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
|
|
private static var archiveURL = DraftsManager.documentsDirectory.appendingPathComponent("drafts").appendingPathExtension("plist")
|
|
|
|
static func save() {
|
|
DispatchQueue.global(qos: .utility).async {
|
|
let encoder = PropertyListEncoder()
|
|
let data = try? encoder.encode(shared)
|
|
try? data?.write(to: archiveURL, options: .noFileProtection)
|
|
}
|
|
}
|
|
|
|
static func load() -> DraftsManager {
|
|
let decoder = PropertyListDecoder()
|
|
if let data = try? Data(contentsOf: archiveURL),
|
|
let draftsManager = try? decoder.decode(DraftsManager.self, from: data) {
|
|
return draftsManager
|
|
}
|
|
return DraftsManager()
|
|
}
|
|
|
|
private init() {}
|
|
|
|
required init(from decoder: Decoder) throws {
|
|
let container = try decoder.container(keyedBy: CodingKeys.self)
|
|
|
|
if let dict = try? container.decode([UUID: Draft].self, forKey: .drafts) {
|
|
self.drafts = dict
|
|
} else if let array = try? container.decode([Draft].self, forKey: .drafts) {
|
|
self.drafts = array.reduce(into: [:], { partialResult, draft in
|
|
partialResult[draft.id] = draft
|
|
})
|
|
} else {
|
|
throw DecodingError.dataCorruptedError(forKey: .drafts, in: container, debugDescription: "expected drafts to be a dict or array of drafts")
|
|
}
|
|
}
|
|
|
|
func encode(to encoder: Encoder) throws {
|
|
var container = encoder.container(keyedBy: CodingKeys.self)
|
|
try container.encode(drafts, forKey: .drafts)
|
|
}
|
|
|
|
@Published private var drafts: [UUID: Draft] = [:]
|
|
var sorted: [Draft] {
|
|
return drafts.values.sorted(by: { $0.lastModified > $1.lastModified })
|
|
}
|
|
|
|
func add(_ draft: Draft) {
|
|
drafts[draft.id] = draft
|
|
}
|
|
|
|
func remove(_ draft: Draft) {
|
|
drafts.removeValue(forKey: draft.id)
|
|
}
|
|
|
|
func getBy(id: UUID) -> Draft? {
|
|
return drafts[id]
|
|
}
|
|
|
|
enum CodingKeys: String, CodingKey {
|
|
case drafts
|
|
}
|
|
|
|
}
|