import Foundation
import MastermindPOCCore

final class OverlaySettingsStore: ObservableObject {
    static let backgroundOpacityKey = "overlay.backgroundOpacity"

    @Published private(set) var settings: OverlaySettings

    var onChange: ((OverlaySettings) -> Void)?

    private let defaults: UserDefaults

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

        if defaults.object(forKey: Self.backgroundOpacityKey) == nil {
            settings = .default
        } else {
            settings = OverlaySettings(backgroundOpacity: defaults.double(forKey: Self.backgroundOpacityKey))
        }
    }

    var backgroundOpacity: Double {
        settings.backgroundOpacity
    }

    func updateBackgroundOpacity(_ opacity: Double) {
        let nextSettings = OverlaySettings(backgroundOpacity: opacity)
        settings = nextSettings
        defaults.set(nextSettings.backgroundOpacity, forKey: Self.backgroundOpacityKey)
        onChange?(nextSettings)
    }
}
