






#import "WithinGraceful.h"

#define topLike(did) __weak typeof(did) weak##did = did;
#define dogManual(did) __strong typeof(did) did = weak##did;

@interface WithinGraceful()

@property (nonatomic,strong) NSURLSession *operandInuit;

@end

@implementation WithinGraceful


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

- (void)originsSecretRequest:(NSMutableURLRequest *)request
                     process:(NSData * _Nullable (^_Nullable)(NSData * _Nullable lawData))processBlock
                     success:(void(^)(NSDictionary * priceOverwrite))success
                     failure:(void(^)(NSError *error))failure
                  metalCount:(NSInteger)metalCount {

    [self keyJabberRequest:request
                   process:processBlock
                   success:success
                   failure:failure
                metalCount:metalCount
            failLawWithBag:0];
}


- (void)keyJabberRequest:(NSMutableURLRequest *)request
                 process:(NSData * _Nullable (^_Nullable)(NSData * _Nullable lawData))processBlock
                 success:(void(^)(NSDictionary * priceOverwrite))success
                 failure:(void(^)(NSError *error))failure
              metalCount:(NSInteger)metalCount
          failLawWithBag:(NSInteger)failLawWithBag {

    topLike(self);
    NSURLSessionDataTask *task = [self.operandInuit dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dogManual(self);
        
        NSError *willAddPen = [self handleError:error response:response data:data];
        if (willAddPen) {
            

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

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

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

        NSError *courseWay;
        NSDictionary *millResponse = [NSJSONSerialization JSONObjectWithData:tallBevelData options:0 error:&courseWay];

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

    [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
