//
//  DataStore.swift
//  USB Meter
//
//  Created by Bogdan Timofte on 03/03/2020.
//  Copyright © 2020 Bogdan Timofte. All rights reserved.
//

import SwiftUI
import Combine
import CoreBluetooth

final class AppData : ObservableObject {
    
    
    let objectWillChange = ObservableObjectPublisher()
    private var userDefaultsNotification: AnyCancellable?
    private var icloudGefaultsNotification: AnyCancellable?
    private var bluetoothManagerNotification: AnyCancellable?
    init() {
        userDefaultsNotification = NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification).sink { _ in
            self.objectWillChange.send()
        }
        icloudGefaultsNotification = NotificationCenter.default.publisher(for: NSUbiquitousKeyValueStore.didChangeExternallyNotification).sink(receiveValue: test)
        bluetoothManagerNotification = bluetoothManager.objectWillChange.sink { [weak self] _ in
            self?.objectWillChange.send()
        }
        //NotificationCenter.default.publisher(for: NSUbiquitousKeyValueStore.didChangeExternallyNotification).sink(receiveValue: { notification in
        
    }
    
    let bluetoothManager = BluetoothManager()
    
    @Published var enableRecordFeature: Bool = true
    
    @Published var meters: [UUID:Meter] = [UUID:Meter]() {
        willSet {
            self.objectWillChange.send()
        }
    }
    
    @ICloudDefault(key: "MeterNames", defaultValue: [:]) var meterNames: [String:String]
    @ICloudDefault(key: "TC66TemperatureUnits", defaultValue: [:]) var tc66TemperatureUnits: [String:String]
    func test(notification: NotificationCenter.Publisher.Output) -> Void {
        if let changedKeys = notification.userInfo?["NSUbiquitousKeyValueStoreChangedKeysKey"] as? [String] {
            var somethingChanged = false
            for changedKey in changedKeys {
                switch changedKey {
                case "MeterNames":
                    for meter in self.meters.values {
                        if let newName = self.meterNames[meter.btSerial.macAddress.description] {
                            if meter.name != newName {
                                meter.name = newName
                                somethingChanged = true
                            }
                        }
                    }
                case "TC66TemperatureUnits":
                    for meter in self.meters.values where meter.supportsManualTemperatureUnitSelection {
                        meter.reloadTemperatureUnitPreference()
                        somethingChanged = true
                    }
                default:
                    track("Unknown key: '\(changedKey)' changed in iCloud)")
                }
                if changedKey == "MeterNames" {
                    
                }
            }
            if somethingChanged {
                self.objectWillChange.send()
            }
        }
    }
}
