import Foundation

class Settings {
    private static let defaults = UserDefaults.standard
    public static let shared = Settings()
    
    var user: User {
        didSet {
            if let json = try? JSONEncoder().encode(self.user) {
                Settings.defaults.set(json, forKey: "user")
                Settings.defaults.synchronize()
            }
        }
    }
    
    var recognizeAlternativeOrder: Bool = false {
        didSet {
            Settings.defaults.set(self.recognizeAlternativeOrder, forKey: "recognizeAlternativeOrder")
            Settings.defaults.synchronize()
        }
    }
    
    var recognizeShortenedNumbers: Bool = false {
        didSet {
            Settings.defaults.set(self.recognizeShortenedNumbers, forKey: "recognizeShortenedNumbers")
            Settings.defaults.synchronize()
        }
    }
    
    var defaultRegion: String = "" {
        didSet {
            Settings.defaults.set(self.defaultRegion, forKey: "defaultRegion")
            Settings.defaults.synchronize()
        }
    }
    
    var recordBeep: Bool = false {
        didSet {
            Settings.defaults.set(self.recordBeep, forKey: "recordBeep")
            Settings.defaults.synchronize()
        }
    }

    var showDebugInfo: Bool = false {
        didSet {
            Settings.defaults.set(self.showDebugInfo, forKey: "showDebugInfo")
            Settings.defaults.synchronize()
        }
    }
    
    init() {
        UserDefaults.standard.register(defaults: [
            "recognizeAlternativeOrder": false,
            "recognizeShortenedNumbers": false,
            "defaultRegion": "161",
            "recordBeep": false,
            "showDebugInfo": false
        ])
        
        self.user = Settings.getUser()
        self.recognizeAlternativeOrder = Settings.defaults.bool(forKey: "recognizeAlternativeOrder")
        self.recognizeShortenedNumbers = Settings.defaults.bool(forKey: "recognizeShortenedNumbers")
        self.defaultRegion = Settings.defaults.string(forKey: "defaultRegion") ?? "161"
        self.recordBeep = Settings.defaults.bool(forKey: "recordBeep")
        self.showDebugInfo = Settings.defaults.bool(forKey: "showDebugInfo")
    }
    
    private static func getUser() -> User {
        guard let data = Settings.defaults.data(forKey: "user") else { return User() }
        return (try? JSONDecoder().decode(User.self, from: data)) ?? User()
    }
}
