//
//  JDUserDefaults.m
//  JasonDevelop
//
//  Created by Jason Lee on 2/4/15.
//  Copyright (c) 2015 JasonDevelop. All rights reserved.
//

#import "JDUserDefaults.h"

@interface JDUserDefaults () {
    NSMutableDictionary *_userData;
}
@end

@implementation JDUserDefaults

- (id)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super init])
    {
        _userData = [aDecoder decodeObjectForKey:@"userData"];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)coder
{
    [coder encodeObject:_userData forKey:@"userData"];
}

- (void)setObject:(id)object forKey:(id<NSCopying>)aKey {
    if (object == nil) {
        object = [NSNull null];
    }

    [_userData setObject:object forKey:aKey];
}

- (id)objectForKey:(id)aKey {
    id object = [_userData objectForKey:aKey];

    return !object || [[NSNull null] isEqual:object] ? nil : object;
}

- (void)setBool:(BOOL)value forKey:(id<NSCopying>)aKey {
    [_userData setObject:value ? ksYES : ksNO forKey:aKey];
}

- (BOOL)boolForKey:(id)aKey {
    id obj = [_userData objectForKey:aKey];
    return obj ? [obj boolValue] : NO;
}

- (void)setInteger:(NSInteger)value forKey:(id<NSCopying>)aKey {
    [_userData setObject:[NSNumber numberWithInt:(int)value]  forKey:aKey];
}

- (NSInteger)integerForKey:(id)aKey {
    id obj = [_userData objectForKey:aKey];
    return obj ? [obj integerValue] : NO;
}


- (void)synchronize {

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *writeData = [NSKeyedArchiver archivedDataWithRootObject:_userData];
    [defaults setObject:writeData forKey:@"LOCAL_USER_DATA"];

    [defaults synchronize];
}

- (void)syncronizeObject:(id)object forKey:(id<NSCopying>)aKey {
    [self setObject:object forKey:aKey];
    [self synchronize];
}

#pragma mark - Singleton

+ (JDUserDefaults *)defaults {

    static JDUserDefaults *sharedUserDefaults = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedUserDefaults = [[self alloc] init];
    });
    return sharedUserDefaults;
}

- (id)init {
    if (self = [super init]) {

        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSData *dataLocal = [defaults objectForKey:@"LOCAL_USER_DATA"];
        _userData = [NSKeyedUnarchiver unarchiveObjectWithData:dataLocal];

        if (!_userData) {
            _userData = [NSMutableDictionary new];
        }
    }
    return self;
}

@end
