//
//  KeychainItemManager.m
//  ZhiJi
//
//  Created by 明津李 on 2020/6/8.
//  Copyright © 2020 Company. All rights reserved.
//

#import "KeychainItemManager.h"
#import "KeychainItemWrapper.h"
#import "Data.h"
#import <AdSupport/AdSupport.h>

NSString * const User_nickName = @"NickName";
NSString * const User_identifier = @"Identifier";
NSString * const User_Login = @"Login";

@implementation KeychainItemManager

+ (void)ReadUUIDAndNickName{
    
//    [self removeUUIDAndNickName]; return;
    
    KeychainItemWrapper *keychain = [[KeychainItemWrapper alloc] initWithIdentifier:User_Login accessGroup:nil];

    Data * data = [[Data alloc]init];
    [data InitPlist];

    [keychain setObject:@" " forKey:(__bridge id)(kSecAttrAccount)];
    [keychain setObject:@" " forKey:(__bridge id)(kSecValueData)];
    
    if ([[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]){
        NSString *idfa = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
        [data WirteDic:idfa Key:@"idfa"];
    }
    
    if (![keychain objectForKey:(__bridge id)kSecAttrService]) {
        
        NSString * nickName = [self getNickName];
        NSString * identifier = [self getUUID];
        
        NSDictionary * dic = @{User_nickName:nickName, User_identifier:identifier};
        NSString * infoStr = [self convertToJsonData:dic];
        
        [keychain setObject:infoStr forKey:(__bridge id)kSecAttrService];
        
        [data WirteDic:nickName Key:User_nickName];
        [data WirteDic:identifier Key:User_identifier];
    }else{
        
        NSString * infoStr = [keychain objectForKey:(__bridge id)kSecAttrService];
        NSDictionary * infoDic = [self dictionaryWithJsonString:infoStr];
        if (infoDic) {
            [data WirteDic:[infoDic objectForKey:User_nickName] Key:User_nickName];
            [data WirteDic:[infoDic objectForKey:User_identifier] Key:User_identifier];
        }
    }
}

+ (void)removeUUIDAndNickName{
    KeychainItemWrapper *keychain = [[KeychainItemWrapper alloc] initWithIdentifier:User_Login accessGroup:nil];
    [keychain resetKeychainItem];
    
    Data * data = [[Data alloc] init];
    [data removeDicForKey:User_identifier];
    [data removeDicForKey:User_nickName];
}

+ (NSString *)getUUID{
    return [NSString stringWithFormat:@"%@", [self UUID]];
}

+ (NSString *)UUID{
    CFUUIDRef uuid = CFUUIDCreate(NULL);
    assert(uuid != NULL);
    CFStringRef uuidStr = CFUUIDCreateString(NULL, uuid);
    
    NSLog(@"uuidStr------》%@",uuidStr);
    return (__bridge NSString *)(uuidStr);
}

+ (NSString *)getNickName{
    NSString * nickName = [self randomStringWithLength:10];
    return [NSString stringWithFormat:@"ZJ%@", nickName];
}

+ (NSString *)randomStringWithLength:(NSInteger)len{
    NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    NSMutableString *randomString = [NSMutableString stringWithCapacity: len];
    
    for (NSInteger i = 0; i < len; i++) {
        [randomString appendFormat: @"%C", [letters characterAtIndex: arc4random_uniform([letters length])]];
    }
    return randomString;
}

+ (NSString *)convertToJsonData:(NSDictionary *)dict{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString{
    if (jsonString == nil)
    {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; NSError *err; NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}


@end
 
