






#import "HashSendRanked.h"

#define turnOne(who) __weak typeof(who) weak##who = who;
#define answerSaw(who) __strong typeof(who) who = weak##who;

@interface HashSendRanked()

@property (nonatomic,strong) NSURLSession *tapIntrinsic;

@end

@implementation HashSendRanked


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

- (void)swapSmoothingRequest:(NSMutableURLRequest *)request
                     process:(NSData * _Nullable (^_Nullable)(NSData * _Nullable carData))processBlock
                     success:(void(^)(NSDictionary * freeIcyHourOff))success
                     failure:(void(^)(NSError *error))failure
                  mountCount:(NSInteger)mountCount {

    [self rankPanelRequest:request
                   process:processBlock
                   success:success
                   failure:failure
                mountCount:mountCount
            sheLossyYetAdd:0];
}


- (void)rankPanelRequest:(NSMutableURLRequest *)request
                 process:(NSData * _Nullable (^_Nullable)(NSData * _Nullable carData))processBlock
                 success:(void(^)(NSDictionary * freeIcyHourOff))success
                 failure:(void(^)(NSError *error))failure
              mountCount:(NSInteger)mountCount
          sheLossyYetAdd:(NSInteger)sheLossyYetAdd {

    turnOne(self);
    NSURLSessionDataTask *task = [self.tapIntrinsic dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        answerSaw(self);
        
        NSError *cursorOnce = [self handleError:error response:response data:data];
        if (cursorOnce) {
            

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

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

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

        NSError *wasOrigin;
        NSDictionary *fourResponse = [NSJSONSerialization JSONObjectWithData:boyfriendData options:0 error:&wasOrigin];

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

    [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
