//
//  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 {
    private var icloudGefaultsNotification: AnyCancellable?
    private var bluetoothManagerNotification: AnyCancellable?

    init() {
        icloudGefaultsNotification = NotificationCenter.default.publisher(for: NSUbiquitousKeyValueStore.didChangeExternallyNotification).sink(receiveValue: test)
        bluetoothManagerNotification = bluetoothManager.objectWillChange.sink { [weak self] _ in
            self?.scheduleObjectWillChange()
        }
        //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]()
    
    @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 {
                scheduleObjectWillChange()
            }
        }
    }

    private func scheduleObjectWillChange() {
        DispatchQueue.main.async { [weak self] in
            self?.objectWillChange.send()
        }
    }
}
