//
//  JavenQNManager.m
//  ALand
//
//  Created by Z on 16/5/3.
//  Copyright © 2016年 Z. All rights reserved.
//

#import "JavenQNManager.h"
#import <QiniuSDK.h>
#import "GTM_Base64.h"
#include <CommonCrypto/CommonCrypto.h>
#import "NSData+EncodeAdditions.h"
#import "UIImage+Helper.h"

//测试key
//#define kAK @"mRX5pK-bCChgNMxeiC_VlRgSFLuz_WbLT3OyViuh"
//#define kSK @"m8XQ8FjLiUY38pgDUzjHApdJ4YpgdlpmRT6FAwAg"

//正式key
#define kAK @"ufPuIR1b_gWCgaIjD_R1ujfl7Djy1VpKoCrHXBxc"
#define kSK @"2JR4SjeRpQp7rxroympYg3iglFB08nEojHGae80c"

@interface JavenQNManager ()
@property (nonatomic, strong) QNUploadManager *upManager;
@property (nonatomic, strong) QNUploadOption *option;
@property (nonatomic, copy) NSString *token;


@end

@implementation JavenQNManager

+ (instancetype)shareInstance {
    static JavenQNManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[JavenQNManager alloc] init];
        
        manager.option = [[QNUploadOption alloc] initWithMime:@"image/jpeg" progressHandler:nil params:nil checkCrc:NO cancellationSignal:nil];
        manager.upManager =[[QNUploadManager alloc]init];
    });
    return manager;
}


- (void)upLoadImage:(UIImage *)image isMD5Name:(BOOL)isMD5Name name:(NSString *)imageName commpelete:(void(^)(NSString *key))commpelete {
    

    NSString *AK =kAK;
    NSString *SK = kSK;
    
    
    self.token = [self makeToken:AK secretKey:SK];
    
    UIImage *imgNewWidth = [image scaledToWidth:200];
    NSData *data = [imgNewWidth scaledToSpaceMaxSize:20];
    
    NSString *name;
    if (isMD5Name) {
        name = [NSString stringWithFormat:@"%@.jpg", [data md5String]];
    }else{
        name = imageName;
    }
    
    
    [self.upManager putData:data key:name token:self.token
              complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                  NSLog(@"info = %@\n", info);
                  NSLog(@"key = %@\n",key);
                  NSLog(@"resp = %@\n", resp);
                  if (commpelete) {
                      commpelete(key);
                  }
                  
                  
              } option:self.option];
}


- (NSString *)makeToken:(NSString *)accessKey secretKey:(NSString *)secretKey
{
    CLog(@"$$---------->生成token");
    const char *secretKeyStr = [secretKey UTF8String];
    
    NSString *policy = [self marshal];
    
    NSData *policyData = [policy dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString *encodedPolicy = [GTM_Base64 stringByWebSafeEncodingData:policyData padded:TRUE];
    const char *encodedPolicyStr = [encodedPolicy cStringUsingEncoding:NSUTF8StringEncoding];
    
    char digestStr[CC_SHA1_DIGEST_LENGTH];
    bzero(digestStr, 0);
    
    CCHmac(kCCHmacAlgSHA1, secretKeyStr, strlen(secretKeyStr), encodedPolicyStr, strlen(encodedPolicyStr), digestStr);
    
    NSString *encodedDigest = [GTM_Base64 stringByWebSafeEncodingBytes:digestStr length:CC_SHA1_DIGEST_LENGTH padded:TRUE];
    
    NSString *token = [NSString stringWithFormat:@"%@:%@:%@",  accessKey, encodedDigest, encodedPolicy];
    
    CLog(@"$$---------->生成token完成");
    return token;//得到了token
}


- (NSString *)marshal
{
    time_t deadline;
    time(&deadline);//返回当前系统时间
    //@property (nonatomic , assign) int expires; 怎么定义随你...
    deadline += 3600; // +3600秒,即默认token保存1小时.
    
    NSNumber *deadlineNumber = [NSNumber numberWithLongLong:deadline];
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    //users是我开辟的公共空间名（即bucket），aaa是文件的key，
    //按七牛“上传策略”的描述：    <bucket>:<key>，表示只允许用户上传指定key的文件。在这种格式下文件默认允许“修改”，若已存在同名资源则会被覆盖。如果只希望上传指定key的文件，并且不允许修改，那么可以将下面的 insertOnly 属性值设为 1。
    //所以如果参数只传users的话，下次上传key还是aaa的文件会提示存在同名文件，不能上传。
    //传users:aaa的话，可以覆盖更新，但实测延迟较长，我上传同名新文件上去，下载下来的还是老文件。
    [dic setObject:@"aland244" forKey:@"scope"];//根据
    
    [dic setObject:deadlineNumber forKey:@"deadline"];
    
    NSString *json = [dic mj_JSONString];
    
    return json;
}

@end
