//
//  MMAutoUploadTool.m
//  DKCamera_Example
//
//  Created by nana on 2020/9/26.
//  Copyright © 2020 304635659@qq.com. All rights reserved.
//

#import "MMAutoUploadTool.h"
#import <AliyunOSSiOS/AliyunOSSiOS.h>

@interface MMAutoUploadTool()
@property (nonatomic,strong)dispatch_queue_t dkQueue;
@property (nonatomic,strong)dispatch_source_t dktimer;
@end

@implementation MMAutoUploadTool

+ (instancetype)sharedManager {
    static MMAutoUploadTool *sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager = [[MMAutoUploadTool alloc] init];
    });
    return sharedManager;
}

- (void)setupDKEnvironmen {
    __weak __typeof__(self) weakSelf = self;
    dispatch_queue_t queue = dispatch_queue_create("com.idankee.DKAutoUpdateDataTool", DISPATCH_QUEUE_SERIAL);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf taskData];
    });
    dispatch_resume(timer);
    self.dktimer = timer;
}


- (void)taskData {

    if (self.timeblock) {
        __weak __typeof__(self) weakSelf = self;
        self.timeblock(^(NSString *objectKey,NSData *imageData, void (^ c1Block)(NSString * i2)) {
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            
                NSString *endpoints = strongSelf.endPoint;
                  OSSCustomSignerCredentialProvider *provider = [[OSSCustomSignerCredentialProvider alloc] initWithImplementedSigner:^NSString *(NSString *contentToSign, NSError *__autoreleasing *error) {
                      
                      // 用户应该在此处将需要签名的字符串发送到自己的业务服务器(AK和SK都在业务服务器保存中,从业务服务器获取签名后的字符串)
                      OSSFederationToken *token = [OSSFederationToken new];
                      
                
                      token.tAccessKey =strongSelf.AccessKey;
                      token.tSecretKey =strongSelf.SecretKey;
                      
                      NSString *signedContent = [OSSUtil sign:contentToSign withToken:token];
                      return signedContent;
                  }];
                  
                OSSClient * client  = [[OSSClient alloc] initWithEndpoint:endpoints credentialProvider:provider];
                
                OSSPutObjectRequest * put = [OSSPutObjectRequest new];
                // required fields

                put.bucketName = strongSelf.BucketName;
            //    NSString *objectKeys = [NSString stringWithFormat:@"User/%@.jpg",[self getNowTimeTimestamp]];

                put.objectKey = objectKey;
                //put.uploadingFileURL = [NSURL fileURLWithPath:fullPath];
                put.uploadingData = imageData;
//                put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
//                    NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
//                };
                OSSTask * putTask = [client putObject:put];
                
                [putTask continueWithBlock:^id(OSSTask *task) {
                    task = [client presignPublicURLWithBucketName:strongSelf.BucketName
                                                    withObjectKey:objectKey];
                                       
                    NSError * error = nil;
                    BOOL isExist = [client doesObjectExistInBucket:strongSelf.BucketName objectKey:objectKey error:&error];
                    if (!isExist) {
                        [NSThread sleepForTimeInterval:20.0];
                    }
//                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (isExist) {
                            c1Block([NSString stringWithFormat:@"%@/%@",[strongSelf domain],objectKey]);
                        } else {
                            c1Block(nil);
                        }
                        
//                    });

                    return nil;
                }];
                [putTask waitUntilFinished];

        });
    }
}
- (NSString *)domain {

      int index = 0;
               
      NSMutableString *urlString = [[NSMutableString alloc] initWithString:self.endPoint];
      if ([urlString hasPrefix:@"https://"]) {
           index = 8;
      }else if([urlString hasPrefix:@"http://"]){
           index = 7;
      }
      [urlString insertString:[NSString stringWithFormat:@"%@.",self.BucketName] atIndex:index];
    
    return urlString;
}

@end
