//
//  GMCookieManager.m
//  Gengmei
//
//  Created by wangyang on 2017/11/14.
//  Copyright © 2017年 更美互动信息科技有限公司. All rights reserved.
//

#import "GMCookieManager.h"
#import "AppDelegate.h"
#import "GMKey.h"
#import "AppDelegate+SDK.h"

@implementation GMCookieManager

+ (NSDictionary<NSString *, NSString *> *)requestHeaderFields {
    NSDictionary *requestHeaderFields = [NSHTTPCookie requestHeaderFieldsWithCookies:[self cookieWithGMToken]];
    return requestHeaderFields;
}

+ (NSArray<NSHTTPCookie *> *)cookieWithGMToken {
    [NSHTTPCookieStorage sharedHTTPCookieStorage].cookieAcceptPolicy = NSHTTPCookieAcceptPolicyAlways;
    NSHTTPCookie *gmTokenCookie = [self createGMTokenCookie];
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:gmTokenCookie];
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:APIHOST]];
    return cookies;
}

+ (NSHTTPCookie *)createGMTokenCookie {
    NSString *deviceId = [UIDevice deviceId];
#if defined DEBUG
    NSString *lastNum = [[NSUserDefaults standardUserDefaults] objectForKey:@"device_id"];
    if ([lastNum isNonEmpty]) {
        deviceId = [deviceId stringByReplacingCharactersInRange:NSMakeRange(deviceId.length - 1, 1) withString:lastNum];
    }
#elif defined RELEASE
    NSString *lastNum = [[NSUserDefaults standardUserDefaults] objectForKey:@"device_id"];
    if ([lastNum isNonEmpty]) {
        deviceId = [deviceId stringByReplacingCharactersInRange:NSMakeRange(deviceId.length - 1, 1) withString:lastNum];
    }
#endif
    NSString *timestamp =  [NSString stringWithFormat:@"%ld", (long)floor([[NSDate date] timeIntervalSince1970])];
    NSString *token = [[NSString stringWithFormat:@"%@%@%@", deviceId, timestamp, accessKey] stringFromMD5];
    NSString *salt = [token substringWithRange:NSMakeRange(6, 6)];
    NSString *accessToken = [NSString stringWithFormat:@"%@%@", salt, timestamp];
#ifdef  DEBUG
//    NSDictionary *debugSessionDic = @{NSHTTPCookieName: @"sessionid",
//                                      NSHTTPCookieValue: @"tuo699ihff1wgamupb25layu88nq5t4b",
//                                      NSHTTPCookieDomain: [GMServerDomains domain],
//                                      NSHTTPCookiePath: @"/"};
//    NSHTTPCookie *deviceInfoCookie = [NSHTTPCookie cookieWithProperties:debugSessionDic];
//    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:deviceInfoCookie];
#endif
    NSMutableDictionary *properties = [NSMutableDictionary dictionary];
    [properties setObject:@"_gm_token" forKey:NSHTTPCookieName];
    [properties setObject:accessToken forKey:NSHTTPCookieValue];
    [properties setObject:[GMServerDomains domain] forKey:NSHTTPCookieDomain];
    [properties setObject:@"/" forKey:NSHTTPCookiePath];
    NSHTTPCookie *accessCookie = [[NSHTTPCookie alloc] initWithProperties:properties];
    return accessCookie;
}


+ (void)setDeviceInfoCookie {
    // 将默认query放到cookie中
    NSString *query = @"";//[[AppDelegate shareInstance] urlCommonParameters];
    if ([query hasPrefix:@"?"]) {
        query = [query substringFromIndex:1];
    }
    NSDictionary *deviceInfoProperties = @{NSHTTPCookieName: @"device_info",
                                           NSHTTPCookieValue: query,
                                           NSHTTPCookieDomain: [GMServerDomains domain],
                                           NSHTTPCookiePath: @"/"};
    NSHTTPCookie *deviceInfoCookie = [NSHTTPCookie cookieWithProperties:deviceInfoProperties];
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:deviceInfoCookie];
}

+ (void)saveSessionId:(NSString *)sessionId domain:(NSString *)domain {
    if (sessionId == nil || domain == nil) {
        return;
    }
#ifdef DEBUG
//    sessionId = @"tuo699ihff1wgamupb25layu88nq5t4b";
#endif
    NSDictionary *properties = @{NSHTTPCookieName: @"sessionid",
                                 NSHTTPCookieValue: sessionId,
                                 NSHTTPCookieDomain: domain,
                                 NSHTTPCookiePath: @"/",
                                 NSHTTPCookieExpires: [[NSDate date] dateByAddingTimeInterval:3600 * 24 * 365]};
    NSHTTPCookie *headeringCookie = [NSHTTPCookie cookieWithProperties:properties];
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:headeringCookie];
}
@end
