//
//  HWMNonceManager.m
//  HWMUISDKNativeDemo
//
//  Created by guomeng on 2022/2/10.
//  Copyright © 2022 Huawei Technologies Co. Ltd. All rights reserved.
//

#import "HWMNonceManager.h"
#import "HWMAppKeyManager.h"


#define HTTP_URL @"https://api.meeting.huaweicloud.com/"

@interface HWMNonceManager ()

@property (nonatomic, copy) NSString *userId;

@property (nonatomic, strong) AFHTTPSessionManager *manager;

@end

@implementation HWMNonceManager

+ (instancetype)shareInstance {
    static dispatch_once_t onceToken;
    static HWMNonceManager *manager = nil;
    dispatch_once(&onceToken, ^{
        manager = [[HWMNonceManager alloc] init];
    });
    return manager;
}

- (instancetype)init {
    if (self = [super init]) {
        self.manager = [self manager];
    }
    return self;
}

+ (void)getNonceWithParams:(NSDictionary *)params success:(void (^)(NSString * _Nonnull))success failure:(void (^)(NSError * _Nonnull))failure {
    
    [HWMNonceManager shareInstance].userId = params[@"userId"];
    
    NSString *nonce = params[@"nonce"];
    NSString *signature = params[@"signature"];
    
    AFHTTPSessionManager *manager = [HWMNonceManager shareInstance].manager;
    NSString *auth = [NSString stringWithFormat:@"HMAC-SHA256 signature=%@", signature];
    [manager.requestSerializer setValue:auth forHTTPHeaderField:@"Authorization"];
    NSString *url = [NSString stringWithFormat:@"%@%@", HTTP_URL, @"v2/usg/acs/auth/appauth"];
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic addEntriesFromDictionary:params];
    dic[@"appId"] = [HWMAppKeyManager shareInstance].appId;
    dic[@"expireTime"] = @(0);
    dic[@"nonce"] = nonce;
    dic[@"clientType"] = @(72);
    dic[@"corpId"] = @"";
    
    
    [manager POST:url parameters:dic headers:nil progress:^(NSProgress *_Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask *_Nonnull task, id _Nullable responseObject) {
        NSDictionary *jsonDict = [self getJsonFromResponse:responseObject];
        if ([jsonDict isKindOfClass:[NSDictionary class]] && [jsonDict.allKeys containsObject:@"accessToken"]) {
            NSString *token = jsonDict[@"accessToken"];
            [self getNonceWithToken:token success:success failure:failure];
        } else {
            if (success) {
                success(@"");
            }
        }
    } failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
    
}

+ (void)getNonceWithToken:(NSString *)token success:(void(^)(NSString *))success failure:(void(^)(NSError *))failure {
    
    AFHTTPSessionManager *manager = [HWMNonceManager shareInstance].manager;
    [manager.requestSerializer setValue:token forHTTPHeaderField:@"X-Access-Token"];

    NSString *url = [NSString stringWithFormat:@"%@%@", HTTP_URL, @"v1/usg/acs/auth/portal-ref-nonce"];

    [manager POST:url parameters:nil headers:nil progress:^(NSProgress *_Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask *_Nonnull task, id _Nullable responseObject) {
        NSDictionary *jsonDict = [self getJsonFromResponse:responseObject];
        if ([jsonDict isKindOfClass:[NSDictionary class]] && [jsonDict.allKeys containsObject:@"nonce"]) {
            NSString *nonce = jsonDict[@"nonce"];
            if (success) {
                success(nonce);
            }
        } else {
            if (success) {
                success(@"");
            }
        }
    } failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}

- (AFHTTPSessionManager *)manager {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    AFHTTPRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
    serializer.timeoutInterval = 20;
    [serializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    manager.requestSerializer = serializer;
    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", @"image/png", @"image/jpeg", nil];
    manager.responseSerializer = responseSerializer;
    return manager;
}

+ (NSDictionary *)getJsonFromResponse:(id)responseObj {
    NSData *data = (NSData *)responseObj;
    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    return jsonDict;
}

@end
