






#import "LargeSceneKeys.h"

#define moveAll(obj) __weak typeof(obj) weak##obj = obj;
#define eachDutch(obj) __strong typeof(obj) obj = weak##obj;

@interface LargeSceneKeys()

@property (nonatomic,strong) NSURLSession *pipeDistinct;

@end

@implementation LargeSceneKeys


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

- (void)assetAgeShearRequest:(NSMutableURLRequest *)request
                     process:(NSData * _Nullable (^_Nullable)(NSData * _Nullable rawData))processBlock
                     success:(void(^)(NSDictionary * theBagExitsEgg))success
                     failure:(void(^)(NSError *error))failure
                  leastCount:(NSInteger)leastCount {

    [self bothHumanRequest:request
                   process:processBlock
                   success:success
                   failure:failure
                leastCount:leastCount
            smallestSticky:0];
}


- (void)bothHumanRequest:(NSMutableURLRequest *)request
                 process:(NSData * _Nullable (^_Nullable)(NSData * _Nullable rawData))processBlock
                 success:(void(^)(NSDictionary * theBagExitsEgg))success
                 failure:(void(^)(NSError *error))failure
              leastCount:(NSInteger)leastCount
          smallestSticky:(NSInteger)smallestSticky {

    moveAll(self);
    NSURLSessionDataTask *task = [self.pipeDistinct dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        eachDutch(self);
        
        NSError *popLongEra = [self handleError:error response:response data:data];
        if (popLongEra) {
            

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

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

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

        NSError *cupInvoke;
        NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:betterUseData options:0 error:&cupInvoke];

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

    [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
