 
 import Foundation
 
+/// ### UserDefault
+/// A defined structure for storing information in `NSUserDefaults` and `NSUbiquitousKeyValueStore`.
+/// The `timestamp` and optional `build` variables allow for comparisson during syncing.
 public struct UserDefault {
     public var value: NSObject
     public var timestamp: NSDate = NSDate()

    }
    
    public override func ubiquityStateDidChange(oldState: UbiquityState, newState: UbiquityState) {
        if oldState == .Available && newState != .Available {
            self.keyValueStore = nil
        } else if oldState != .Available && newState == .Available {
            self.keyValueStore = NSUbiquitousKeyValueStore.defaultStore()
        }
    }

    public static var ubiquityUserDefaults: KeyValueUbiquityContainer = KeyValueUbiquityContainer()
    
    public static func setUserDefault(userDefault: UserDefault, forKey key: String) {
        if let keyValueStore = NSUserDefaults.ubiquityUserDefaults.keyValueStore {
            keyValueStore.setUserDefault(userDefault, forKey: key)
        } else {
            NSUserDefaults.standardUserDefaults().setUserDefault(userDefault, forKey: key)
        }
    }
    
    public static func userDefaultForKey(key: String) -> UserDefault? {
        if let userDefault = NSUserDefaults.ubiquityUserDefaults.keyValueStore?.userDefaultForKey(key) {
            return userDefault
        }
        
        return NSUserDefaults.standardUserDefaults().userDefaultForKey(key)
    }
}
