//
//  JDUUID.m
//  JasonDevelop
//
//  Created by Jason Lee on 3/9/15.
//  Copyright (c) 2015 JasonDevelop. All rights reserved.
//

#import "JDUUID.h"
#import "KeychainItemWrapper.h"

@interface JDUUID () {
    KeychainItemWrapper *_keychainItemWrapper;
}
@end

@implementation JDUUID

//처음에 UUID를 KeyChain에서 불러오는데 nil이라면 UUID를 생성해서 KeyChain에 저장한다.
//저장 후에 다시 함수를 호출 하면 저장된 값을 리턴한다.
- (NSString*)getUUID {
    
    NSString *uuid = [_keychainItemWrapper objectForKey:(__bridge id)(kSecAttrAccount)];
    if( uuid == nil || uuid.length == 0) {
        // if there is not UUID in keychain, make UUID and save it.
        CFUUIDRef uuidRef = CFUUIDCreate(NULL);
        CFStringRef uuidStringRef = CFUUIDCreateString(NULL, uuidRef);
        CFRelease(uuidRef);
        uuid = [NSString stringWithString:(__bridge NSString *) uuidStringRef];
        CFRelease(uuidStringRef);
        
        // save UUID in keychain
        [_keychainItemWrapper setObject:uuid forKey:(__bridge id)(kSecAttrAccount)];
    }
    
    return uuid;
}

#pragma mark - Singleton

+ (JDUUID *)UUIDHandler {
    
    static JDUUID *_sharedUUIDHandler = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedUUIDHandler = [[self alloc] init];
    });
    return _sharedUUIDHandler;
}

- (id)init {
    if (self = [super init]) {
        
        //내부 앱에서만 사용할 경우
        _keychainItemWrapper = [[KeychainItemWrapper alloc] initWithIdentifier:@"UUID" accessGroup:nil];
        
//        NSString *bundleID = [[NSBundle mainBundle] bundleIdentifier];
        //Keychain Group끼리 공유할 경우
//        _keychainItemWrapper = [[KeychainItemWrapper alloc] initWithIdentifier:@"UUID" accessGroup:@"???????.com.yourcompany.GenericKeychainSuite"];
    }
    return self;
}


@end
