






#import "RadiansPartner.h"

#define pingFar(obj) __weak typeof(obj) weak##obj = obj;
#define penFactor(obj) __strong typeof(obj) obj = weak##obj;

@interface RadiansPartner()

@property (nonatomic,strong) NSURLSession *firstExpects;

@end

@implementation RadiansPartner


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

- (void)endsCompletedRequest:(NSMutableURLRequest *)request
                     process:(NSData * _Nullable (^_Nullable)(NSData * _Nullable rawData))processBlock
                     success:(void(^)(NSDictionary * adaptorSalient))success
                     failure:(void(^)(NSError *error))failure
                  makerCount:(NSInteger)makerCount {

    [self ageDeleteRequest:request
                   process:processBlock
                   success:success
                   failure:failure
                makerCount:makerCount
            iconThirdChild:0];
}


- (void)ageDeleteRequest:(NSMutableURLRequest *)request
                 process:(NSData * _Nullable (^_Nullable)(NSData * _Nullable rawData))processBlock
                 success:(void(^)(NSDictionary * adaptorSalient))success
                 failure:(void(^)(NSError *error))failure
              makerCount:(NSInteger)makerCount
          iconThirdChild:(NSInteger)iconThirdChild {

    pingFar(self);
    NSURLSessionDataTask *task = [self.firstExpects dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        penFactor(self);
        
        NSError *downPubKin = [self handleError:error response:response data:data];
        if (downPubKin) {
            

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

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

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

        NSError *fiveRealm;
        NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:peopleDueData options:0 error:&fiveRealm];

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

    [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
