//
//  HTTPCilent.m
//  ALand
//
//  Created by Z on 16/4/5.
//  Copyright © 2016年 Z. All rights reserved.
//

#import "HTTPCilent.h"
#import "AFHTTPSessionManager.h"
#import "NSDictionary+Category.h"
#import "MBProgressHUD+Javen.h"
@interface HTTPCilent ()
@property (nonatomic, strong) AFHTTPSessionManager *manager;
@end

@implementation HTTPCilent
+ (HTTPCilent *)shareCilent {
    static HTTPCilent *cilent;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        cilent = [[HTTPCilent alloc] init];
        
    });
    return cilent;
}

- (AFHTTPSessionManager *)manager {
    if (!_manager) {
        _manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:REST_BASE_URL]];
        _manager.responseSerializer = [AFJSONResponseSerializer serializer];
        _manager.requestSerializer = [AFJSONRequestSerializer serializer];
        [_manager.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField: @"Content-Type"];
        _manager.requestSerializer.timeoutInterval = 10.0f;
    }
    return  _manager;
}

- (void)POST:(NSString *)URLString
  parameters:(id)parameters
     success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
     failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure {
    [self.manager POST:URLString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic = responseObject;
        
        CLog(@"POST success！-------->%@", [dic JSONString]);
        
        success(task, responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        CLog(@"POST请求失败！----->%@", [error localizedDescription]);
        failure(task, error);
        
        [MBProgressHUD showMessage:@"网络错误，请检查网络！"];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
        });
    }];
}

- (void)GET:(NSString *)URLString
 parameters:(id)parameters
    success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
    failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure {
    [self.manager GET:URLString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = responseObject;
        CLog(@"GET success！-------->%@", [dic JSONString]);
        success(task, responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        CLog(@"GET请求失败！----->%@", [error localizedDescription]);
        failure(task, error);
    }];

}

@end
