//
//  OSSHelper.m
//  patrol
//
//  Created by 曹云霄 on 16/8/23.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "OSSHelper.h"
#import <AVFoundation/AVFoundation.h>


static OSSClient *client;

@implementation OSSHelper

+ (void)initialize {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:kUser.configModel.uploadType.accessKey secretKey:kUser.configModel.uploadType.secretKey];
        OSSClientConfiguration * conf = [OSSClientConfiguration new];
        conf.maxRetryCount = 3;
        conf.maxConcurrentRequestCount = 1;
        conf.enableBackgroundTransmitService = YES;
        conf.timeoutIntervalForRequest = 15;
        conf.timeoutIntervalForResource = 24 * 60 * 60;
        client = [[OSSClient alloc] initWithEndpoint:kUser.configModel.uploadType.endPoint credentialProvider:credential clientConfiguration:conf];
    });
}


static NSError * _Nullable extracted(OSSTask *task) {
    return task.error;
}

/**
 *  上传文件
 *
 *  @param objectKey Key
 *  @param data      Data
 *  @param type      同步、异步
 *  @param progress  上传进度
 *  @param success   返回
 */
+ (void)uploadFileObjectWithKey:(NSString *)objectKey data:(NSData *)data type:(OSSHelperOperationType)type progress:(void (^)(double progress))progress success:(void (^)(OSSTask *task))success error:(void(^)(NSError *error))error
{
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    put.bucketName = kUser.configModel.uploadType.bucketName;
    put.objectKey = objectKey;
    put.uploadingData = data;
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend){
        double totalBytesSentFloat = totalBytesSent;
        double totalBytesExpectedToSendFloat =
        totalBytesExpectedToSend;
        progress(totalBytesSentFloat / totalBytesExpectedToSendFloat);
    };
    OSSTask * putTask = [client putObject:put];
    if (type == OSSHelperOperationTypeSynchronous) {
        [putTask waitUntilFinished];
    }
    [putTask continueWithSuccessBlock:^id(OSSTask *task){
        success(task);
        return nil;
    }];
    [putTask continueWithBlock:^id(OSSTask *task) {
        if (!extracted(task)) {
            NSLog(@"upload object success!");
        } else {
            error(task.error);
        }
        return nil;
    }];
}


/**
 *  下载附件
 *
 *  @param ObjectKey OSSkey
 *  @param type      同步、异步
 *  @param progress  进度
 *  @param success   成功回调
 */
+ (void)downloadObject:(NSString *)ObjectKey type:(OSSHelperOperationType)type progress:(void (^)(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))progress success:(id (^)(OSSTask *task))success error:(void(^)(NSError *))error
{
    OSSGetObjectRequest * request = [OSSGetObjectRequest new];
    request.bucketName = kUser.configModel.uploadType.bucketName;
    request.objectKey = ObjectKey;
    request.downloadProgress = progress;
    NSArray *array = [ObjectKey componentsSeparatedByString:@"/"];
    request.downloadToFileURL = [NSURL fileURLWithPath:[kPathCaches stringByAppendingPathComponent:[NSString stringWithFormat:@"cache/%@",[array lastObject]]]];
    OSSTask * getTask = [client getObject:request];
    if (type == OSSHelperOperationTypeSynchronous) {
        [getTask waitUntilFinished];
    }
    [getTask continueWithSuccessBlock:success];
    [getTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
            NSLog(@"upload object success!");
        } else {
            error(task.error);
        }
        return nil;
    }];
}


/**
 *  获取OSS的ObjectKey
 *
 *  @return NSString
 */
+ (NSString *)getOSSObjectKey
{
    NSMutableString *ObjectKey = [[NSMutableString alloc]init];
    NSString *userName = kUser.f_user_uuid;
    if(userName!=nil && userName.length>0)
    {
        [ObjectKey appendString:userName];
    }
    NSDate *dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval  a = [dat timeIntervalSince1970] * 1000;  //  *1000 是精确到毫秒，不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a]; //转为字符型
    if(timeString!=nil && timeString.length>0)
    {
        [ObjectKey appendString:timeString];
    }
    if(ObjectKey.length<=userName.length||ObjectKey.length<=timeString.length)
    {
        return nil;
    }
    else
    {
        return ObjectKey;
    }
}


/**
 *  获取OSS的ObjectKey，多个时，用index区分
 *
 *  @param index index
 *
 *  @return NSString
 */
+ (NSString *)getOSSObjectKey:(NSInteger)index
{
    NSMutableString *ObjectKey = [[NSMutableString alloc]init];
    NSString *userName = kUser.f_user_uuid;
    if(userName!=nil && userName.length>0)
    {
        [ObjectKey appendString:userName];
    }
    NSDate *dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a = [dat timeIntervalSince1970] * 1000;  //  *1000 是精确到毫秒，不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a+index]; //转为字符型
    if(timeString!=nil && timeString.length>0)
    {
        [ObjectKey appendString:timeString];
    }
    if(ObjectKey.length<=userName.length||ObjectKey.length<=timeString.length)
    {
        return nil;
    }
    else
    {
        return ObjectKey;
    }
}

/**
 *  获取文件名称
 *
 *  @param type 区分图片和视频<image/video>
 *
 *  @return NSString
 */
+ (NSString *)getOSSObjectKeyWithtype:(NSString *)type
{
    NSString *osskey = [[self class] getOSSObjectKey];
    NSString *urlString = [NSString stringWithFormat:@"iOS%@.%@",osskey,type];
    return urlString;
}


/**
 *  获取文件名称,多个时通过index区分
 *
 *  @param type 区分图片和视频<image/video>
 *
 *  @return NSString
 */
+ (NSString *)getOSSObjectKeyWithtype:(NSString *)type index:(NSInteger)index
{
    NSString *osskey = [[self class] getOSSObjectKey:index];
    NSString *urlString = [NSString stringWithFormat:@"iOS%@.%@",osskey,type];
    return urlString;
}


/**
 *  获得完整的图片路径
 *
 *  @param OSSKey OSSKey
 *
 *  @return 路径
 */
+ (NSString *)getCompleteImageURLWithOSSkey:(NSString *)OSSKey
{
    NSArray *ossStringArray = [kUser.configModel.uploadType.endPoint componentsSeparatedByString:@"//"];
    NSString *string = [NSString stringWithFormat:@"http://%@.%@/%@/%@/%@",kUser.configModel.uploadType.bucketName,[ossStringArray lastObject],kUser.configModel.uploadType.imagePath,[[NSDate date] yearMonthDayString],OSSKey];
    return string;
}

/**
 *  获得完整的视频路径
 *
 *  @param OSSKey OSSKey
 *
 *  @return 路径
 */
+ (NSString *)getCompleteVideoURLWithOSSkey:(NSString *)OSSKey
{
    NSArray *ossStringArray = [kUser.configModel.uploadType.endPoint componentsSeparatedByString:@"//"];
    NSString *string = [NSString stringWithFormat:@"http://%@.%@/%@/%@/%@",kUser.configModel.uploadType.bucketName,[ossStringArray lastObject],kUser.configModel.uploadType.videoPath,[[NSDate date] yearMonthDayString],OSSKey];
    return string;
}













@end
