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

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


NSString * const accessKey = @"LTAI6Km6HG7tXBBq";
NSString * const secretKey = @"xTrZGR9Q1V2Wguk10551upmDROU64k";
NSString * const endPoint = @"http://oss-cn-shanghai.aliyuncs.com";
NSString * const bucketName = @"oppledev";


/**
 *  OSS图片文件路径
 */
NSString * const OSSImagePath = @"image/opple_forum/";

/**
 *  OSS视频文件路径
 */
NSString * const OSSVideoPath = @"video/opple_forum/";



static OSSClient *client;

@implementation OSSHelper

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


/**
 *  上传图片
 *
 *  @param ObjectKey Key
 *  @param data      Data
 *  @param type      同步、异步
 *  @param progress  上传进度
 *  @param success   返回
 */
+ (void)uploadImageObjectWithKey:(NSString *)ObjectKey data:(NSData *)data type:(OSSHelperOperationType)type progress:(void (^)(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))progress success:(id (^)(OSSTask *task))success error:(void (^)(NSError *))error
{
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    put.bucketName = bucketName;
    put.objectKey = [NSString stringWithFormat:@"%@%@/%@",OSSImagePath,[[NSDate date] yearMonthDayString],ObjectKey];
    //判断文件在OSS是否存在
    if ([client doesObjectExistInBucket:put.bucketName objectKey:ObjectKey error:nil]) {
        success([OSSTask new]);
    }else
    {
        put.uploadingData = data;
        put.uploadProgress = progress;
        OSSTask * putTask = [client putObject:put];
        if (type == OSSHelperOperationTypeSynchronous) {
            [putTask waitUntilFinished];
        }
        [putTask continueWithSuccessBlock:success];
        [putTask continueWithBlock:^id(OSSTask *task) {
            if (!task.error) {
                NSLog(@"upload object success!");
            } else {
                error(task.error);
            }
            return nil;
        }];
    }
}

/**
 *  上传视频
 *
 *  @param ObjectKey Key
 *  @param data      Data
 *  @param type      同步、异步
 *  @param progress  上传进度
 *  @param success   返回
 */
+ (void)uploadVideoObjectWithKey:(NSString *)ObjectKey data:(NSData *)data type:(OSSHelperOperationType)type progress:(void (^)(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))progress success:(id (^)(OSSTask *task))success error:(void (^)(NSError *))error
{
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    put.bucketName = bucketName;
    put.objectKey = [NSString stringWithFormat:@"%@%@/%@",OSSVideoPath,[[NSDate date] yearMonthDayString],ObjectKey];
    //判断文件在OSS是否存在
    if ([client doesObjectExistInBucket:put.bucketName objectKey:ObjectKey error:nil]) {
        success([OSSTask new]);
    }else
    {
        put.uploadingData = data;
        put.uploadProgress = progress;
        OSSTask * putTask = [client putObject:put];
        if (type == OSSHelperOperationTypeSynchronous) {
            [putTask waitUntilFinished];
        }
        [putTask continueWithSuccessBlock:success];
        [putTask continueWithBlock:^id(OSSTask *task) {
            if (!task.error) {
                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 = 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 = [Shoppersmanager manager].shoppers.employee.fid;
    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 = [Shoppersmanager manager].shoppers.employee.fid;
    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 = [endPoint componentsSeparatedByString:@"//"];
    return [NSString stringWithFormat:@"http://%@.%@/%@%@/%@",bucketName,[ossStringArray lastObject],OSSImagePath,[[NSDate date] yearMonthDayString],OSSKey];
}

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













@end
