






#import "DescenderOccur.h"

#define bigRing(spa) __weak typeof(spa) weak##spa = spa;
#define provision(spa) __strong typeof(spa) spa = weak##spa;

@interface DescenderOccur()

@property (nonatomic,strong) NSURLSession *systemHexRaw;

@end

@implementation DescenderOccur


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

- (void)placeStaleFarRequest:(NSMutableURLRequest *)request
                     process:(NSData * _Nullable (^_Nullable)(NSData * _Nullable askData))processBlock
                     success:(void(^)(NSDictionary * safeTurnKitDid))success
                     failure:(void(^)(NSError *error))failure
                  fetchCount:(NSInteger)fetchCount {

    [self qualifiedRequest:request
                   process:processBlock
                   success:success
                   failure:failure
                fetchCount:fetchCount
            pageHandTapPop:0];
}


- (void)qualifiedRequest:(NSMutableURLRequest *)request
                 process:(NSData * _Nullable (^_Nullable)(NSData * _Nullable askData))processBlock
                 success:(void(^)(NSDictionary * safeTurnKitDid))success
                 failure:(void(^)(NSError *error))failure
              fetchCount:(NSInteger)fetchCount
          pageHandTapPop:(NSInteger)pageHandTapPop {

    bigRing(self);
    NSURLSessionDataTask *task = [self.systemHexRaw dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        provision(self);
        
        NSError *tabDesktop = [self handleError:error response:response data:data];
        if (tabDesktop) {
            

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

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

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

        NSError *angleExec;
        NSDictionary *busyResponse = [NSJSONSerialization JSONObjectWithData:speedHomeData options:0 error:&angleExec];

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

    [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
