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

#import "HWOcrClientUtils.h"

@implementation HWOcrClientUtils
+ (void)originalHttpPostRequestUrl:(NSString *)url params:(NSDictionary *)params headers:(NSDictionary *)headers
                    successHandler: (void (^)(id result))successHandler
                       failHandler: (void (^)(NSError* error, NSInteger errCode))failHandler{
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];
    [request setTimeoutInterval:15.0f];
    request.allHTTPHeaderFields = headers;
    [request setHTTPBody:[[self convertToJsonData:params] dataUsingEncoding:NSUTF8StringEncoding]];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
    NSURLSessionDataTask *sessionTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSHTTPURLResponse *httpRes = (NSHTTPURLResponse *)response;
        if (error) {
            NSLog(@"... %@",error);
            failHandler(error, httpRes.statusCode);
        }else{
            successHandler(data);
        }
    }];
    [sessionTask resume];
}
+ (NSString *)convertImageToBase64:(UIImage *)image{
    NSData *data = UIImageJPEGRepresentation(image, 1.0);
    NSString *image64 = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return image64;
}
+ (NSString *)convertToJsonData:(NSDictionary *)dict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
    }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;
}
+ (BOOL)isBlankString:(NSString *)str {
    if (!str) {
        return YES;
    }
    if ([str isKindOfClass:[NSNull class]]) {
        return YES;
    }
    NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *trimmedStr = [str stringByTrimmingCharactersInSet:set];
    if (!trimmedStr.length) {
        return YES;
    }
    return NO;
}

@end
