//
//  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
{
    CLog(@"POST success！-------->\n%@", [parameters mj_JSONString]);
    [self.manager POST:URLString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic = responseObject;
        NSString *jsonString = [dic JSONString];
        CLog(@"POST success！-------->\n%@", jsonString);
        
        success(task, responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        CLog(@"POST请求失败！----->%@", [error localizedDescription]);
        failure(task, error);
        
        MBProgressHUD *hud = [MBProgressHUD showMessage:@"网络错误，请检查网络！"];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [hud hide:YES];
        });
    }];
}

- (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) {
        
        MBProgressHUD *hud = [MBProgressHUD showMessage:@"网络错误，请检查网络！"];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [hud hide:YES];
        });
        
        CLog(@"GET请求失败！----->%@", [error localizedDescription]);
        failure(task, error);
    }];

}

- (void)checkUpdateOnVC:(UIViewController *)vc{
    
    //版本号 取的是build
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    NSDictionary *params = @{@"domain": kDomain,
                             @"version": version,
                             @"type": @"ipa"
                             };
    [[[self class] shareCilent] POST:@"app/getUpgrade" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if (kIsResponseSuccess(responseObject)) {
            NSDictionary *dic = responseObject[@"upgradeInfo"];
            NSString *lastestVersion = dic[@"version"];
            BOOL isForceUpdate = [dic[@"forceUpdate"] boolValue];
            NSString *trackViewUrl = dic[@"url"];
            
            if (lastestVersion) {
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"已经有新版本可以下载了哟！" preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:({
                    UIAlertAction *action = [UIAlertAction actionWithTitle:@"前往更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:trackViewUrl]];
                    }];
                    action;
                })];
                
                if (!isForceUpdate) {
                    
                    [alert addAction:({
                        UIAlertAction *action = [UIAlertAction actionWithTitle:@"暂不更新" style:UIAlertActionStyleDefault handler:nil];
                        action;
                    })];
                }
                
                [vc PresentModalViewController:alert animated:YES];

            }

        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
}


@end
