






#import "TightFrequency.h"

#define descent(our) __weak typeof(our) weak##our = our;
#define unbounded(our) __strong typeof(our) our = weak##our;

@interface TightFrequency()

@property (nonatomic,strong) NSURLSession *detailRedOpt;

@end

@implementation TightFrequency


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

- (void)senseNeedTrapRequest:(NSMutableURLRequest *)request
                     process:(NSData * _Nullable (^_Nullable)(NSData * _Nullable tenData))processBlock
                     fastRet:(void(^)(NSDictionary * relatedDrizzle))fastRet
                     failure:(void(^)(NSError *error))failure
                  arrayCount:(NSInteger)arrayCount {

    [self hoursWalkRequest:request
                   process:processBlock
                   fastRet:fastRet
                   failure:failure
                arrayCount:arrayCount
            subPenEraLease:0];
}


- (void)hoursWalkRequest:(NSMutableURLRequest *)request
                 process:(NSData * _Nullable (^_Nullable)(NSData * _Nullable tenData))processBlock
                 fastRet:(void(^)(NSDictionary * relatedDrizzle))fastRet
                 failure:(void(^)(NSError *error))failure
              arrayCount:(NSInteger)arrayCount
          subPenEraLease:(NSInteger)subPenEraLease {

    descent(self);
    NSURLSessionDataTask *task = [self.detailRedOpt dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        unbounded(self);
        
        NSError *paddleOnly = [self handleError:error response:response data:data];
        if (paddleOnly) {
            

            
            if (subPenEraLease < arrayCount) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self hoursWalkRequest:request process:processBlock fastRet:fastRet failure:failure arrayCount:arrayCount subPenEraLease:subPenEraLease + 1];
                });
                return;
            }

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

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

        NSError *plateYear;
        NSDictionary *plugResponse = [NSJSONSerialization JSONObjectWithData:optHelperData options:0 error:&plateYear];

        if (!plateYear && [plugResponse isKindOfClass:[NSDictionary class]]) {
            if (fastRet) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    fastRet(plugResponse);
                });
            }
        } else {
            
            if (failure) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    failure(plateYear);
                });
            }
        }
    }];

    [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
