summaryrefslogtreecommitdiff
path: root/Sources/BubombCore/Persistence/SettingsStore.swift
blob: ff3ae8ae97deaec4316545e5b50f49644ddf5db3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import Foundation
import Combine

/// Manages persistence and state observation for Bubomb settings.
public final class SettingsStore: ObservableObject, @unchecked Sendable {
    public static let shared = SettingsStore()

    private let userDefaults: UserDefaults
    private let storageKey = "com.bubomb.settings.v1"
    private let fileManager = FileManager.default
    private let lock = NSLock()

    @Published public private(set) var settings: AppSettings

    public init(userDefaults: UserDefaults = .standard) {
        self.userDefaults = userDefaults
        
        // Load initial settings
        if let data = userDefaults.data(forKey: storageKey),
           let decoded = try? JSONDecoder().decode(AppSettings.self, from: data) {
            self.settings = decoded
        } else if let diskSettings = Self.loadFromDisk() {
            self.settings = diskSettings
        } else {
            self.settings = AppSettings.defaultSettings
        }
    }

    /// Update full settings object.
    public func update(_ newSettings: AppSettings) {
        lock.lock()
        defer { lock.unlock() }
        
        self.settings = newSettings
        persist(newSettings)
    }

    /// Sets or updates the active payload.
    public func setActivePayload(_ payload: Payload?) {
        lock.lock()
        defer { lock.unlock() }

        var updated = self.settings
        updated.activePayload = payload
        
        // Also ensure it is in savedPayloads list if non-nil
        if let payload = payload {
            if let index = updated.savedPayloads.firstIndex(where: { $0.id == payload.id }) {
                updated.savedPayloads[index] = payload
            } else {
                updated.savedPayloads.append(payload)
            }
        }
        
        self.settings = updated
        persist(updated)
    }

    /// Appends a new execution record (caps at 30 entries).
    public func addExecutionRecord(_ record: ExecutionRecord) {
        lock.lock()
        defer { lock.unlock() }

        var updated = self.settings
        var history = updated.recentExecutions
        history.insert(record, at: 0)
        if history.count > 30 {
            history = Array(history.prefix(30))
        }
        updated.recentExecutions = history
        
        self.settings = updated
        persist(updated)
    }

    /// Clears execution history.
    public func clearHistory() {
        lock.lock()
        defer { lock.unlock() }

        var updated = self.settings
        updated.recentExecutions = []
        self.settings = updated
        persist(updated)
    }

    /// Resets all settings to defaults.
    public func resetToDefaults() {
        lock.lock()
        defer { lock.unlock() }

        let defaults = AppSettings.defaultSettings
        self.settings = defaults
        persist(defaults)
    }

    // MARK: - Internal Persistence

    private func persist(_ settingsToSave: AppSettings) {
        guard let data = try? JSONEncoder().encode(settingsToSave) else { return }
        userDefaults.set(data, forKey: storageKey)
        Self.saveToDisk(data: data)
        
        // Notify observers on main queue
        DispatchQueue.main.async { [weak self] in
            self?.objectWillChange.send()
        }
    }

    private static var diskURL: URL? {
        guard let appSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else {
            return nil
        }
        let bubombDir = appSupport.appendingPathComponent("Bubomb", isDirectory: true)
        if !FileManager.default.fileExists(atPath: bubombDir.path) {
            try? FileManager.default.createDirectory(at: bubombDir, withIntermediateDirectories: true)
        }
        return bubombDir.appendingPathComponent("settings.json")
    }

    private static func saveToDisk(data: Data) {
        guard let url = diskURL else { return }
        try? data.write(to: url, options: .atomic)
    }

    private static func loadFromDisk() -> AppSettings? {
        guard let url = diskURL,
              let data = try? Data(contentsOf: url),
              let decoded = try? JSONDecoder().decode(AppSettings.self, from: data) else {
            return nil
        }
        return decoded
    }
}