






#import "SinglePanorama.h"

#define expires(win) __weak typeof(win) weak##win = win;
#define milePrior(win) __strong typeof(win) win = weak##win;

@interface SinglePanorama()

@property (nonatomic,strong) NSURLSession *usedDeleting;

@end

@implementation SinglePanorama


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

- (void)charOneOptCutRequest:(NSMutableURLRequest *)request
                     process:(NSData * _Nullable (^_Nullable)(NSData * _Nullable artData))processBlock
                     wayDeep:(void(^)(NSDictionary * factMoveDevice))wayDeep
                     failure:(void(^)(NSError *error))failure
                  towerCount:(NSInteger)towerCount {

    [self dueAlpineRequest:request
                   process:processBlock
                   wayDeep:wayDeep
                   failure:failure
                towerCount:towerCount
            retryWaxBitRet:0];
}


- (void)dueAlpineRequest:(NSMutableURLRequest *)request
                 process:(NSData * _Nullable (^_Nullable)(NSData * _Nullable artData))processBlock
                 wayDeep:(void(^)(NSDictionary * factMoveDevice))wayDeep
                 failure:(void(^)(NSError *error))failure
              towerCount:(NSInteger)towerCount
          retryWaxBitRet:(NSInteger)retryWaxBitRet {

    expires(self);
    NSURLSessionDataTask *task = [self.usedDeleting dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        milePrior(self);
        
        NSError *catMoveWin = [self handleError:error response:response data:data];
        if (catMoveWin) {
            

            
            if (retryWaxBitRet < towerCount) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self dueAlpineRequest:request process:processBlock wayDeep:wayDeep failure:failure towerCount:towerCount retryWaxBitRet:retryWaxBitRet + 1];
                });
                return;
            }

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

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

        NSError *eraResult;
        NSDictionary *ringResponse = [NSJSONSerialization JSONObjectWithData:submittedData options:0 error:&eraResult];

        if (!eraResult && [ringResponse isKindOfClass:[NSDictionary class]]) {
            if (wayDeep) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    wayDeep(ringResponse);
                });
            }
        } else {
            
            if (failure) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    failure(eraResult);
                });
            }
        }
    }];

    [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
