import Foundation

protocol WorkspaceStoreType {
    func loadWorkspaceSummaries() -> [WorkspaceSummary]
    func saveWorkspaceSummaries(_ summaries: [WorkspaceSummary])
}

protocol ScreenAssignmentStoreType {
    func loadScreenAssignments() -> [ScreenID: WorkspaceID]
    func saveScreenAssignments(_ assignments: [ScreenID: WorkspaceID])
}

struct UserDefaultsWorkspaceStore: WorkspaceStoreType {
    private let defaults: UserDefaults
    private let encoder = JSONEncoder()
    private let decoder = JSONDecoder()

    init(defaults: UserDefaults = .standard) {
        self.defaults = defaults
    }

    func loadWorkspaceSummaries() -> [WorkspaceSummary] {
        guard let data = defaults.data(forKey: NotchSettings.Keys.workspaceSummaries),
              let summaries = try? decoder.decode([WorkspaceSummary].self, from: data) else {
            return []
        }

        return summaries
    }

    func saveWorkspaceSummaries(_ summaries: [WorkspaceSummary]) {
        guard let data = try? encoder.encode(summaries) else { return }
        defaults.set(data, forKey: NotchSettings.Keys.workspaceSummaries)
    }
}

struct UserDefaultsScreenAssignmentStore: ScreenAssignmentStoreType {
    private let defaults: UserDefaults
    private let encoder = JSONEncoder()
    private let decoder = JSONDecoder()

    init(defaults: UserDefaults = .standard) {
        self.defaults = defaults
    }

    func loadScreenAssignments() -> [ScreenID: WorkspaceID] {
        guard let data = defaults.data(forKey: NotchSettings.Keys.screenAssignments),
              let assignments = try? decoder.decode([ScreenID: WorkspaceID].self, from: data) else {
            return [:]
        }

        return assignments
    }

    func saveScreenAssignments(_ assignments: [ScreenID: WorkspaceID]) {
        guard let data = try? encoder.encode(assignments) else { return }
        defaults.set(data, forKey: NotchSettings.Keys.screenAssignments)
    }
}
