//
//  ALTranslateTool.m
//  GMAlpha
//
//  Created by zhb on 2018/11/23.
//  Copyright © 2018 Gengmei. All rights reserved.
//

#import "ALTranslateTool.h"
#import "AFNetworking.h"
#import <CommonCrypto/CommonHMAC.h>


#define TRANS_APPID           20181121000237465
#define TRANS_APPKEY          @"yEtzQH2tTBTBb5OzSb9F"
#define TRANS_API_URL         @"https://fanyi-api.baidu.com/api/trans/vip/translate"
#define TRANS_SALT            1435660288

@interface ALTranslateTool ()
@property (nonatomic, assign) NSInteger scount;
@end

@implementation ALTranslateTool


+ (instancetype)shareInstance
{
    static dispatch_once_t onceToken;
    static id instance = nil;
    dispatch_once(&onceToken, ^{
        instance = [[[self class] alloc] init];
    });
    
    return instance;
}

-(void)transStr:(NSString *)string toLanguage:(NSString *)language successBlock:(void (^)(NSString *resultString))successBlock failBlock:(void (^)(void))failBlock
{
    NSArray *tempA = [string componentsSeparatedByString:@"\n"];
    NSMutableArray *strArray = [NSMutableArray arrayWithArray:tempA];
    for (NSInteger i = 0; i < strArray.count;) {
        NSString *subStr = strArray[i];
        if ([subStr isEqualToString:@""]) {
            [strArray removeObjectAtIndex:i];
        }else {
            i++;
        }
    }
    NSString *q = [strArray componentsJoinedByString:@"\n"];//要翻译的内容
    NSString *sign = [self sign:q];
    NSString *url = [self urlWithSign:sign Q:q toLanguage:language];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];//AFN网络请求
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {
        NSArray *trans_result = responseObject[@"trans_result"];
        NSMutableArray *resultArray = [NSMutableArray array];
        for (NSDictionary *objDict in trans_result) {
            NSString *resultStr = objDict[@"dst"] ? : @"";
            [resultArray addObject:resultStr];
        }
        if (resultArray.count != strArray.count) {
            if (failBlock){
                failBlock();
            }
            return ;
        }
        //成功:
        NSString *resultString = [resultArray componentsJoinedByString:@"\n"];
        if (successBlock) {
            successBlock(resultString);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (failBlock){
            failBlock();
        }
    }];
}
-(void)transStr:(NSString *)string toLanguage:(NSString *)language backBlock:(void (^)(NSString *resultString, NSError *error))block {
    NSArray *tempA = [string componentsSeparatedByString:@"\n"];
    NSMutableArray *strArray = [NSMutableArray arrayWithArray:tempA];
    for (NSInteger i = 0; i < strArray.count;) {
        NSString *subStr = strArray[i];
        if ([subStr isEqualToString:@""]) {
            [strArray removeObjectAtIndex:i];
        }else {
            i++;
        }
    }
    NSString *q = [strArray componentsJoinedByString:@"\n"];//要翻译的内容
    NSString *sign = [self sign:q];
    NSString *url = [self urlWithSign:sign Q:q toLanguage:language];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];//AFN网络请求
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {
        NSArray *trans_result = responseObject[@"trans_result"];
        NSMutableArray *resultArray = [NSMutableArray array];
        for (NSDictionary *objDict in trans_result) {
            NSString *resultStr = objDict[@"dst"] ? : @"";
            [resultArray addObject:resultStr];
        }
        if (resultArray.count != strArray.count) {
            NSString *domain = @"com.baidu.translation";
            NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : @"数据错误" };
            NSError *error = [NSError errorWithDomain:domain
                                                 code:-101
                                             userInfo:userInfo];
            if (block) {
                block(nil, error);
            }
            return ;
        }
        //成功:
        NSString *resultString = [resultArray componentsJoinedByString:@"\n"];
        if (block) {
            block(resultString, nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (block) {
            block(nil, error);
        }
    }];
}








//md5 加密
- (NSString *)md5:(NSString *) input {
    const char *cStr = [input UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, (CC_LONG)strlen(cStr), digest ); // This is the md5 call
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return  output;
}


//2.构建原则 appid+q+salt+密钥
- (NSString *)sign:(NSString *)q {
    NSString *temp = [NSString stringWithFormat:@"%ld%@%d%@",TRANS_APPID, q, TRANS_SALT, TRANS_APPKEY];
    //MD5加密
    NSString *sign = [self md5:temp];
    return sign;
}

//3.构建urlString
- (NSString *)urlWithSign:(NSString *)sign Q:(NSString *)q toLanguage:(NSString *)language {
    NSString *from = @"auto";//自动检测需要翻译的语言是哪国语言
    NSString *to = language;//要翻译成哪国语言
    //构建原则 appid+q+salt+密钥
    NSString *urlQ = [q stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];//转化一下
    NSString *result = [NSString stringWithFormat:@"%@?q=%@&from=%@&to=%@&appid=%ld&salt=%d&sign=%@",TRANS_API_URL,  urlQ, from, to, TRANS_APPID, TRANS_SALT, sign];
    return result;
}


@end
