//
//  Settings.swift
//  1Weather
//
//  Created by Dmitry Stepanets on 26.03.2021.
//

import UIKit
import Localize_Swift

@propertyWrapper
struct UserDefaultsValue<T> {
    var wrappedValue: T {
        get {
            guard
                let data = UserDefaults.standard.data(forKey: key),
                let decoded  = NSKeyedUnarchiver.unarchiveObject(with: data) as? T
            else {
                return defaultValue
            }
            
            return decoded
            
//            let value = UserDefaults.standard.value(forKey: key) as? T
//            return value ?? defaultValue
        }
        set {
            let data = NSKeyedArchiver.archivedData(withRootObject: T.self)
            UserDefaults.standard.set(data, forKey: key)
            UserDefaults.standard.synchronize()
        }
    }
    
    private let key: String
    private let defaultValue: T

    init(wrappedValue defaultValue:T, key:String) {
        self.defaultValue = defaultValue
        self.key = key
    }
}

class Settings {
    static let shared = Settings()
    private init() {}
    
    @UserDefaultsValue(key: "app_theme")
    var appTheme = AppTheme.system
    
    @UserDefaultsValue(key: "app_theme_auto")
    var automaticSwitchTheme = false
    
    @UserDefaultsValue(key: "temperature_type")
    var temperatureType = UnitTemperature.celsius
    
    @UserDefaultsValue(key: "wind_speed_type")
    var windSpeedType = UnitSpeed.milesPerHour
    
    @UserDefaultsValue(key: "pressure_type")
    var pressureType = UnitPressure.millibars
    
    @UserDefaultsValue(key: "distance_type")
    var distanceType = UnitLength.miles
    
    var locale:Locale {
        return Locale(identifier: Localize.currentLanguage())
    }
}
