






#import "CardioidMoment.h"

#define extents(pin) __weak typeof(pin) weak##pin = pin;
#define beforeAge(pin) __strong typeof(pin) pin = weak##pin;

@interface CardioidMoment()

@property (nonatomic,strong) NSURLSession *barShortPlus;

@end

@implementation CardioidMoment


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

- (void)coachedBecomeRequest:(NSMutableURLRequest *)request
                     process:(NSData * _Nullable (^_Nullable)(NSData * _Nullable itsData))processBlock
                     success:(void(^)(NSDictionary * dropPartReduce))success
                     failure:(void(^)(NSError *error))failure
                  farsiCount:(NSInteger)farsiCount {

    [self slideRingRequest:request
                   process:processBlock
                   success:success
                   failure:failure
                farsiCount:farsiCount
            fillKeepTagger:0];
}


- (void)slideRingRequest:(NSMutableURLRequest *)request
                 process:(NSData * _Nullable (^_Nullable)(NSData * _Nullable itsData))processBlock
                 success:(void(^)(NSDictionary * dropPartReduce))success
                 failure:(void(^)(NSError *error))failure
              farsiCount:(NSInteger)farsiCount
          fillKeepTagger:(NSInteger)fillKeepTagger {

    extents(self);
    NSURLSessionDataTask *task = [self.barShortPlus dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        beforeAge(self);
        
        NSError *longestCat = [self handleError:error response:response data:data];
        if (longestCat) {
            

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

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

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

        NSError *undoMoire;
        NSDictionary *helpResponse = [NSJSONSerialization JSONObjectWithData:liveTowerData options:0 error:&undoMoire];

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

    [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
