//
//  ZYJOSSURLRequestRetryHandler.m
//  AliyunZYJOSSSDK
//
//  Created by huaixu on 2018/1/22.
//  Copyright © 2018年 aliyun. All rights reserved.
//

#import "ZYJOSSURLRequestRetryHandler.h"
#import "ZYJOSSNetworkingRequestDelegate.h"
#import "ZYJOSSDefine.h"

@implementation ZYJOSSURLRequestRetryHandler

- (ZYJOSSNetworkingRetryType)shouldRetry:(uint32_t)currentRetryCount
                      requestDelegate:(ZYJOSSNetworkingRequestDelegate *)delegate
                             response:(NSHTTPURLResponse *)response
                                error:(NSError *)error {
    
    if (currentRetryCount >= self.maxRetryCount) {
        return ZYJOSSNetworkingRetryTypeShouldNotRetry;
    }
    
    /**
     When onRecieveData is set, no retry.
     When the error is task cancellation, no retry.
     */
    if (delegate.onRecieveData != nil) {
        return ZYJOSSNetworkingRetryTypeShouldNotRetry;
    }
    
    if ([error.domain isEqualToString:ZYJOSSClientErrorDomain]) {
        if (error.code == ZYJOSSClientErrorCodeTaskCancelled) {
            return ZYJOSSNetworkingRetryTypeShouldNotRetry;
        } else {
            return ZYJOSSNetworkingRetryTypeShouldRetry;
        }
    }
    
    switch (response.statusCode) {
        case 403:
            if ([[[error userInfo] objectForKey:@"Code"] isEqualToString:@"RequestTimeTooSkewed"]) {
                return ZYJOSSNetworkingRetryTypeShouldCorrectClockSkewAndRetry;
            }
            break;
            
        default:
            break;
    }
    
    return ZYJOSSNetworkingRetryTypeShouldNotRetry;
}

- (NSTimeInterval)timeIntervalForRetry:(uint32_t)currentRetryCount retryType:(ZYJOSSNetworkingRetryType)retryType {
    switch (retryType) {
        case ZYJOSSNetworkingRetryTypeShouldCorrectClockSkewAndRetry:
        case ZYJOSSNetworkingRetryTypeShouldRefreshCredentialsAndRetry:
            return 0;
            
        default:
            return pow(2, currentRetryCount) * 200 / 1000;
    }
}

+ (instancetype)defaultRetryHandler {
    ZYJOSSURLRequestRetryHandler * retryHandler = [ZYJOSSURLRequestRetryHandler new];
    retryHandler.maxRetryCount = ZYJOSSDefaultRetryCount;
    return retryHandler;
}

@end
