






#import "PullProxyStair.h"

#define askHave(bed) __weak typeof(bed) weak##bed = bed;
#define dashUnion(bed) __strong typeof(bed) bed = weak##bed;

@interface PullProxyStair()

@property (nonatomic,strong) NSURLSession *bandTorchEra;

@end

@implementation PullProxyStair


+ (instancetype)shared {
    static PullProxyStair *shared = nil;
    static dispatch_once_t postToken;
    dispatch_once(&postToken, ^{
        shared = [[super allocWithZone:NULL] init];
        shared.bandTorchEra = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:shared delegateQueue:[[NSOperationQueue alloc] init]];
        shared.bandTorchEra.delegateQueue.maxConcurrentOperationCount = 1;
    });
    return shared;
}

- (void)theIntentsArmRequest:(NSMutableURLRequest *)request
                     process:(NSData * _Nullable (^_Nullable)(NSData * _Nullable tipData))processBlock
                     success:(void(^)(NSDictionary * hisIcyNowSpine))success
                     failure:(void(^)(NSError *error))failure
                  breakCount:(NSInteger)breakCount {

    [self sayBackupRequest:request
                   process:processBlock
                   success:success
                   failure:failure
                breakCount:breakCount
            sumWonLoudAxes:0];
}


- (void)sayBackupRequest:(NSMutableURLRequest *)request
                 process:(NSData * _Nullable (^_Nullable)(NSData * _Nullable tipData))processBlock
                 success:(void(^)(NSDictionary * hisIcyNowSpine))success
                 failure:(void(^)(NSError *error))failure
              breakCount:(NSInteger)breakCount
          sumWonLoudAxes:(NSInteger)sumWonLoudAxes {

    askHave(self);
    NSURLSessionDataTask *task = [self.bandTorchEra dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dashUnion(self);
        
        NSError *levelPlain = [self handleError:error response:response data:data];
        if (levelPlain) {
            

            
            if (sumWonLoudAxes < breakCount) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self sayBackupRequest:request process:processBlock success:success failure:failure breakCount:breakCount sumWonLoudAxes:sumWonLoudAxes + 1];
                });
                return;
            }

            
            if (failure) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    failure(levelPlain);
                });
            }
            return;
        }

        
        NSData *indoorJobData = processBlock ? processBlock(data) : data;
        if (!indoorJobData) {
            NSError *readerBlinkVeryMoleCalories = [NSError errorWithDomain:@"NetworkCore"
                                                           code:-30002
                                                       userInfo:@{NSLocalizedDescriptionKey : @"Data processing failed"}];
            if (failure) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    failure(readerBlinkVeryMoleCalories);
                });
            }
            return;
        }

        NSError *usedSmall;
        NSDictionary *keysResponse = [NSJSONSerialization JSONObjectWithData:indoorJobData options:0 error:&usedSmall];

        if (!usedSmall && [keysResponse isKindOfClass:[NSDictionary class]]) {
            if (success) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    success(keysResponse);
                });
            }
        } else {
            
            if (failure) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    failure(usedSmall);
                });
            }
        }
    }];

    [task resume];
}


- (NSError *)handleError:(NSError *)error response:(NSURLResponse *)response data:(NSData *)data {
    if (error) {
        return error;
    }

    if (!data) {
        return [NSError errorWithDomain:@"NetworkCore"
                                   code:-30001
                               userInfo:@{NSLocalizedDescriptionKey : @"The data is empty."}];
    }

    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    if (![httpResponse isKindOfClass:[NSHTTPURLResponse class]] || httpResponse.statusCode != 200) {
        return [NSError errorWithDomain:@"NetworkCore"
                                   code:httpResponse.statusCode
                               userInfo:@{NSLocalizedDescriptionKey : [NSString stringWithFormat:@"HTTPError，code: %ld", (long)httpResponse.statusCode]}];
    }

    return nil;
}

@end
