//
//  HWOcrClientAKSK.m
//  OCR
//
//  Created by huawei on 2018/10/31.
//  Copyright © 2018/10/31 huawei. All rights reserved.
//

#import "HWOcrClientAKSK.h"
#import "HWOcrClientAKSKSign.h"
#import "HWOcrClientUtils.h"

@interface HWOcrClientAKSK ()
@property (copy,nonatomic) NSString *appKey;
@property (copy,nonatomic) NSString *appSecretKey;
@property (copy,nonatomic) NSString *httpEndPoint;
@end
@implementation HWOcrClientAKSK
- (instancetype)initWithAppKey:(NSString *)appKey AppSecretKey:(NSString *)appSecretKey HttpEndPoint:(NSString *)httpEndPoint{
    if (self = [super init]) {
        _appKey = appKey;
        _appSecretKey = appSecretKey;
        _httpEndPoint = httpEndPoint;
        if ([HWOcrClientUtils isBlankString:_appKey]) {
            NSLog(@"appKey cannot be empty");
            return nil;
        }
        if ([HWOcrClientUtils isBlankString:_appSecretKey]) {
            NSLog(@"appSecretKey cannot be empty");
            return nil;
        }
        if ([HWOcrClientUtils isBlankString:_httpEndPoint]) {
            NSLog(@"httpEndPoint cannot be empty");
            return nil;
        }
    }
    return self;
}
- (void)requestOcrServiceWithUri:(NSString *)uri
                     image: (UIImage *)image
                   options: (NSDictionary *)options
            successHandler: (void (^)(id result))successHandler
               failHandler: (void (^)(NSError* error, NSInteger errCode))failHandler{
  
    if ([HWOcrClientUtils isBlankString:uri]) {
        NSLog(@"uri cannot be empty");
        return;
    }
    if (![image isKindOfClass:[UIImage class]]) {
        NSLog(@"image must be kind of UIImage class");
        return;
    }
    OcrAkSKSignRequest *request = [[OcrAkSKSignRequest alloc] init];
    request.scheme = @"https";
    request.host = self.httpEndPoint;
    request.method = @"POST";
    request.uri = uri;
    NSDictionary *dict2 = @{@"Content-Type":@"application/json"};
    request.headers = [NSMutableDictionary dictionaryWithDictionary:dict2];

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:[HWOcrClientUtils convertImageToBase64:image] forKey:@"image"];
    [params addEntriesFromDictionary:options];
    request.body = [HWOcrClientUtils convertToJsonData:params];
    // aksk sign
    [[HWOcrClientAKSKSign shardService] signWithOcrHttpRequest:request appKey:_appKey  appSecretKey:_appSecretKey];
    NSLog(@"url = %@", [NSString stringWithFormat:@"%@://%@%@",request.scheme,request.host,request.uri]);
    [HWOcrClientUtils originalHttpPostRequestUrl:[NSString stringWithFormat:@"%@://%@%@",request.scheme,request.host,request.uri] params:params headers:request.headers successHandler:^(id result) {
        successHandler(result);
    } failHandler:^(NSError *error, NSInteger errCode) {
        failHandler(error, errCode);
    }];
}

@end
