//
//  ICloudDefault.swift
//  USB Meter
//
//  Created by Bogdan Timofte on 12/04/2020.
//  Copyright © 2020 Bogdan Timofte. All rights reserved.
//

import Foundation
// https://github.com/lobodpav/Xcode11.4Issues/blob/master/Sources/Xcode11.4Test/CloudListener.swift
// https://medium.com/@craiggrummitt/boss-level-property-wrappers-and-user-defaults-6a28c7527cf
@propertyWrapper struct ICloudDefault<T> {
  let key: String
  let defaultValue: T
 
  var wrappedValue: T {
    get {
        return NSUbiquitousKeyValueStore.default.object(forKey: key) as? T ?? defaultValue
    }
    set {
        NSUbiquitousKeyValueStore.default.set(newValue, forKey: key)
        /* MARK: Sincronizarea forțată
            Face ca sincronizarea intre dispozitive mai repidă dar există o limita de update-uri catre iloud
        */
        NSUbiquitousKeyValueStore.default.synchronize()
        track("Pushed into iCloud value: '\(newValue)' for key: '\(key)'")
    }
  }
}
