//
//  NvHttpRequest.m
//  NvCheez
//
//  Created by shizhouhu on 2018/6/5.
//  Copyright © 2018年 shizhouhu. All rights reserved.
//

#import "NvHttpRequest.h"
#import "AFNetworking.h"

#define NV_ASSET_REQUEST_URL    @"http://asset.meishesdk.com:8888/index.php"
#define NV_API_HOST             @"https://api.meishesdk.com/"
#define NV_API_FEEDBACK         @"feedback/index.php?command=feedback"

@implementation NvHttpRequest

static NvHttpRequest *sharedInstance = nil;
static AFHTTPSessionManager *httpSessionManager;
static AFNetworkReachabilityManager *networkManager;

+ (NvHttpRequest *)sharedInstance {
    if (nil != sharedInstance) {
        return sharedInstance;
    }
    
    static dispatch_once_t pred;
    dispatch_once(&pred, ^{
        sharedInstance = [[NvHttpRequest alloc] init];
        networkManager = [AFNetworkReachabilityManager sharedManager];
    });
    
    return sharedInstance;
}

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

+ (AFHTTPSessionManager *)sharedManager {
    if (httpSessionManager)
        return httpSessionManager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 初始化请求管理类
        httpSessionManager = [AFHTTPSessionManager manager];
        httpSessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
        
        // 设置15秒超时 - 取消请求
        httpSessionManager.requestSerializer.timeoutInterval = 15.0;
        [httpSessionManager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        
        // 编码
        httpSessionManager.requestSerializer.stringEncoding = NSUTF8StringEncoding;
        // 缓存策略
        httpSessionManager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
        
        httpSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
        // 支持内容格式
        httpSessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/javascript", @"text/json", @"text/html", nil];
    });
    return httpSessionManager;
}

- (void)getAssetList:(AssetType)assetType
         aspectRatio:(AspectRatio)aspectRatio
          categoryId:(int)categoryId
               page:(int32_t)page
           pageSize:(int32_t)pageSize
       withDelegate:(id<NvHttpRequestDelegate>)delegate
{
    AFHTTPSessionManager *httpSessionManager = [NvHttpRequest sharedManager];
    NSMutableDictionary *params = [self makeRequestParam:assetType aspectRatio:aspectRatio categoryId:categoryId page:page pageSize:pageSize];
    
    [httpSessionManager GET:NV_ASSET_REQUEST_URL
                 parameters:params
                   progress:^(NSProgress * _Nonnull uploadProgress) {
        
                    }
                    success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                        NSError *err = nil;
                        NSDictionary *dicResults = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&err];
                        if(err) {
                            if(delegate && [delegate respondsToSelector:@selector(onGetAssetListFailed:assetType:)]){
                                [delegate onGetAssetListFailed:err assetType:assetType];
                            }
                        }else{
                            int errNo = [[dicResults objectForKey:@"errNo"] intValue];
                            BOOL hasNext = [[dicResults objectForKey:@"hasNext"] boolValue];
                            if(errNo == 0){
                                if(delegate && [delegate respondsToSelector:@selector(onGetAssetListSuccess:assetType:hasNext:)]){
                                    [delegate onGetAssetListSuccess:[dicResults objectForKey:@"list"] assetType:assetType hasNext:hasNext];
                                }
                            } else {
                                if(delegate && [delegate respondsToSelector:@selector(onGetAssetListFailed:assetType:)]){
                                    [delegate onGetAssetListFailed:nil assetType:assetType];
                                }
                            }
                        }
                    }
                    failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                        if(delegate && [delegate respondsToSelector:@selector(onGetAssetListFailed:assetType:)]){
                            [delegate onGetAssetListFailed:error assetType:assetType];
                        }
                    }
     ];
}

- (NSMutableDictionary *)makeRequestParam:(AssetType)assetType
                              aspectRatio:(AspectRatio)aspectRatio
                               categoryId:(int)categoryId
                                     page:(int32_t)page
                                 pageSize:(int32_t)pageSize
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"command"] = @"listMaterial";
    params[@"acceptAspectRatio"] = @(aspectRatio);
    if (assetType == ASSET_CUSTOM_ANIMATED_STICKER) {
        params[@"category"] = @(NV_CATEGORY_ID_CUSTOM);
    } else {
        params[@"category"] = @(categoryId);
    }
    params[@"page"] = @(page);
    params[@"pageSize"] = @(pageSize);
    params[@"lang"] = @"zh_CN";
    if (assetType == ASSET_THEME) {
        params[@"type"] = @1;
    } else if (assetType == ASSET_FILTER) {
        params[@"type"] = @2;
    } else if (assetType == ASSET_CAPTION_STYLE) {
        params[@"type"] = @3;
    } else if (assetType == ASSET_ANIMATED_STICKER) {
        params[@"type"] = @4;
    } else if (assetType == ASSET_VIDEO_TRANSITION) {
        params[@"type"] = @5;
    } else if (assetType == ASSET_CAPTURE_SCENE) {
        params[@"type"] = @8;
    } else if (assetType == ASSET_PARTICLE) {
        params[@"type"] = @9;
    } else if (assetType == ASSET_FACE_STICKER) {
        params[@"type"] = @10;
    } else if (assetType == ASSET_CUSTOM_ANIMATED_STICKER) {
        params[@"type"] = @4;
    } else if (assetType == ASSET_FACE1_STICKER) {
        params[@"type"] = @12;
    }
    
    return params;
}

- (NSURLSessionDownloadTask *) downloadAsset:(NSString*)srcFileUrl
                                 destFileDir:(NSString*)destFileDir
                                withDelegate:(id<NvHttpRequestDelegate>)delegate
                                  downloadID:(NSString*)downloadID
{
    AFURLSessionManager *httpSessionManager = [NvHttpRequest sharedManager];
    NSURL *url = [NSURL URLWithString:srcFileUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionDownloadTask *currentTask = [httpSessionManager downloadTaskWithRequest:request
                                                                               progress:^(NSProgress * _Nonnull downloadProgress) {
        int32_t progress = (int32_t)(downloadProgress.completedUnitCount * 100 / downloadProgress.totalUnitCount);
        if(delegate && [delegate respondsToSelector:@selector(onDonwloadAssetProgress:downloadID:)])
            [delegate onDonwloadAssetProgress:progress downloadID:downloadID];
    }
                                                                            destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSString *filePath = [destFileDir stringByAppendingPathComponent:url.lastPathComponent];
        return [NSURL fileURLWithPath:filePath];
        
    }
                                                                      completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if(delegate){
            if(error){
                if([delegate respondsToSelector:@selector(onDonwloadAssetFailed:downloadFilePath:downloadID:)])
                    [delegate onDonwloadAssetFailed:error downloadFilePath:[filePath absoluteString] downloadID:downloadID];
            } else{
                if([delegate respondsToSelector:@selector(onDonwloadAssetSuccess: downloadFilePath: downloadID:)])
                    [delegate onDonwloadAssetSuccess:TRUE downloadFilePath:[filePath absoluteString] downloadID:downloadID];
            }
        }
    }];

    [currentTask resume];
    return currentTask;
}

- (void)checkNetwork:(id<NvHttpRequestDelegate>)delegate
{
    [networkManager startMonitoring];
    [networkManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        BOOL isNetAvailable = YES;
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: { //未知网络
                isNetAvailable = NO;
                break;
            }
            case AFNetworkReachabilityStatusNotReachable:{//无法联网
                isNetAvailable = NO;
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWWAN:{//手机自带网络
                isNetAvailable = YES;
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWiFi:{//WIFI
                isNetAvailable = YES;
            }
        }
        
        if(delegate && [delegate respondsToSelector:@selector(onCheckNetworkState:)]){
            [delegate onCheckNetworkState:isNetAvailable];
        }
    }];
}

- (void)feedBackWithContent:(NSString *)content withContact:(NSString *)contact withSdkVersion:(NSString *)sdkVersion withDeviceModel:(NSString *)deviceModel withDelegate:(id<NvHttpRequestDelegate>)delegate{
    NSDictionary *body = @{@"content":content,@"contact":contact,@"sdkVersion":sdkVersion,@"deviceModel":deviceModel};
    AFHTTPSessionManager *httpSessionManager = [NvHttpRequest sharedManager];
    httpSessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    [httpSessionManager POST:[NV_API_HOST stringByAppendingString:NV_API_FEEDBACK] parameters:body progress:NULL success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
        [delegate feedBackWithDictionary:dict];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}
@end
