//
//  CloudUploadSession.m
//  zhuxun
//
//  Created by winsoft on 17/6/27.
//
//

#import "CloudUploadSession.h"
#import <MJExtension/MJExtension.h>
#import "HttpRequest.h"
#import "CloudStorageDB.h"
@interface CloudUploadSession()
@property (nonatomic , strong) WSUploadSession *uploadSession;

@property (nonatomic , strong) NSMutableDictionary *successBlocksDict;
@property (nonatomic , strong) NSMutableDictionary *failureBlocksDict;
@property (nonatomic , strong) NSMutableDictionary *progressBlocksDict;

@property (nonatomic , assign) NSOperationQueue *operationQueue;
@property (nonatomic , copy) NSDate *lastRecordTime;
@end
@implementation CloudUploadSession

- (NSMutableDictionary *)successBlocksDict
{
    if (!_successBlocksDict) {
        _successBlocksDict = [NSMutableDictionary dictionary];
    }
    
    return _successBlocksDict;
}

- (NSMutableDictionary *)failureBlocksDict
{
    if (!_failureBlocksDict) {
        _failureBlocksDict = [NSMutableDictionary dictionary];
    }
    
    return _failureBlocksDict;
}

- (NSMutableDictionary *)progressBlocksDict
{
    if (!_progressBlocksDict) {
        _progressBlocksDict = [NSMutableDictionary dictionary];
    }
    
    return _progressBlocksDict;
}


+ (CloudUploadSession *)startUploadFileWithFileDownUpModel:(CSFileDownUpModel *)fileDownUpModel operationQueue:(NSOperationQueue *)operationQueue
{
    CloudUploadSession *cloudUploadSession = [[CloudUploadSession alloc]initCloudUploadSessionWithFileDownUpModel:fileDownUpModel operationQueue:operationQueue];
    
    return cloudUploadSession;
    
}

- (instancetype)initCloudUploadSessionWithFileDownUpModel:(CSFileDownUpModel *)fileDownUpModel operationQueue:(NSOperationQueue *)operationQueue
{
    if (self = [super init]) {
        
        _operationQueue = operationQueue;
        _fileDownUpModel = fileDownUpModel;

        NSString *localFullPath = nil;
        
        if (fileDownUpModel.fileSouce == FileSourceFileLocal) {
            localFullPath = [NSString stringWithFormat:@"%@/%@",fileDownUpModel.fileType == FileTypeOther?FileFolderFullRouter:PhotosMessageDir,fileDownUpModel.localRootPath];
        }else localFullPath = [NSString stringWithFormat:@"%@/%@",CloudStorageFullRouter,fileDownUpModel.localRootPath];
        
        
        [self startUploadFileWithfileDownUpModel:fileDownUpModel localFullPath:localFullPath operationQueue:operationQueue];
    }
    
   
    
    return self;
}

- (void)startUploadFileWithfileDownUpModel:(CSFileDownUpModel *)fileDownUpModel localFullPath:(NSString *)localFullPath operationQueue:(NSOperationQueue *)operationQueue
{
//     __weak typeof(self)weakSelf = self;
    
    [[HttpRequest sharedManager]cloudStorageGetFileUploadURLWithMD5:fileDownUpModel.md5 complete:^(BOOL success, id data, NSError *error) {
        
        NSString *host = [data[@"host"]componentsSeparatedByString:@":"][0];
        NSString *port = [data[@"host"]componentsSeparatedByString:@":"][1];
        if (success && host && port) {
            
            self.uploadSession = [WSUploadSession uploadFileWithServerHost:host port:port fileMD5:fileDownUpModel.md5 uuid:fileDownUpModel.downUpUUID fileSize:fileDownUpModel.size startSize:fileDownUpModel.downUpSize localFileFullPath:localFullPath processBlock:nil successBlock:nil failBlock:nil];
            
//            [operationQueue addOperation:self.uploadSession];
            

            __weak typeof(self)weakself = self;
            
            self.uploadSession.uploadSuccessBlock = ^(NSString* url,long long fileSize,NSString *msgUUID){
            
                
                
                weakself.fileDownUpModel.downUpSize = fileSize;
                [[HttpRequest sharedManager]cloudStorageCreateNewFileWithFileName:fileDownUpModel.name md5:fileDownUpModel.md5 pid:fileDownUpModel.pid delflag:nil ext:fileDownUpModel.ext size:[NSNumber numberWithInteger:fileDownUpModel.size] complete:^(BOOL success, id data, NSError *error) {
                    /*
                     data =     {
                     "_id" = 59546bfd8145020d6ce090bc;
                     delflag = 0;
                     ext = PNG;
                     isdir = 0;
                     md5 = e19af74a289b0973c1e402a9c131dd68;
                     name = "e19af74a289b0973c1e402a9c131dd68.dat?786D74B9-E5B9-47FB-B3D9-F1F7AAA8BBCE.PNG";
                     pid = 594b894f66be760240cac18b;
                     "server_ctime" = 1498704893428;
                     size = 774598;
                     "update_time" = 1498704893428;
                     "user_id" = 7616;
                     };
                     message = "";
                     success = 1;
                     */
                    NSLog(@"%@",error);
                    
                    if (success && data) {
                        
                        weakself.fileDownUpModel.downUpStatus = DownUpStatusSuccess;
                        
#warning 2017-07-25 缺少serverfullpath?
                        CSFileModel *csFileModel = [CSFileModel mj_objectWithKeyValues:data[@"data"]];
                        
                        csFileModel.serverFullPath = weakself.fileDownUpModel.serverFullPath;
                        
                        weakself.fileDownUpModel.sid = csFileModel.sid;
                        
                        // add file to cache
                        [kCloudStorageDB addcsFiletoDB:csFileModel];
                        //update upfilemodel
                        [kCloudStorageDB updateCSDownUpFileIDWithCSFileDownUpModel:weakself.fileDownUpModel sid:csFileModel.sid];
                  
                        [kCloudStorageDB updateCSDownUpFileStatusWithCSFileDownUpModel:weakself.fileDownUpModel];
                        
//                        if (weakself.uploadSuccessBlock) {
//                            weakself.uploadSuccessBlock(url,fileSize,weakself.fileDownUpModel,weakself.fileDownUpModel.downUpUUID);
//                        }
                        
                        int i = 0;
                        for (CSUploadSuccessUIBlock succBlock in weakself.successBlocksDict.allValues) {
                            
                            NSString *key = weakself.successBlocksDict.allKeys[i];
                            if (succBlock) {
                                //一方面,所有的model都注册了,另一方面,有时候多个model公共一个task.
                                succBlock(url,fileSize,weakself.fileDownUpModel,key);
                            }
                            i++;
                        }
                        
                        if (weakself.uploadSuccessDBBlock) {
                            weakself.uploadSuccessDBBlock(url,fileSize,weakself.fileDownUpModel);
                        }
                        
                        
                    }else{
                        
                        weakself.fileDownUpModel.downUpStatus = DownUpStatusFailure;
                        
                        [kCloudStorageDB updateCSDownUpFileStatusWithCSFileDownUpModel:weakself.fileDownUpModel];
                        
                        int i = 0;
                        for (CSUploadFailedUIBlock faiureBlock in weakself.failureBlocksDict.allValues) {
                            
                            NSString *key = weakself.failureBlocksDict.allKeys[i];
                            if (faiureBlock) {
                                //一方面,所有的model都注册了,另一方面,有时候多个model公共一个task.
                                faiureBlock(error.description,weakself.fileDownUpModel,key);
                            }
                            i++;
                        }
                        
                        if (weakself.uploadFailedDBBlock) {
                            weakself.uploadFailedDBBlock (error.description,weakself.fileDownUpModel);
                        }
                        
                     
                        
                        
                    }
                    
                    
                    
                }];
            };
            
            self.uploadSession.uploadProgressBlock = ^(double progress,NSInteger sendedSize, NSString *msgUUID){
            
                weakself.fileDownUpModel.downUpSize = sendedSize;
                
                NSDate *now = [NSDate date];
                
                if (!weakself.lastRecordTime || [now timeIntervalSinceDate:weakself.lastRecordTime] >= 1) {
                    
                    //存储
                    [kCloudStorageDB updateCSDownUpFileStatusWithCSFileDownUpModel:weakself.fileDownUpModel];
                    
                    weakself.lastRecordTime = now;
                    
                    
                }
                
                int i = 0;
                for (CSUploadProgressUIBlock proBlock in weakself.progressBlocksDict.allValues) {
                    
                    NSString *key = weakself.progressBlocksDict.allKeys[i];
                    if (proBlock) {
                        //一方面,所有的model都注册了,另一方面,有时候多个model公共一个task.
                        proBlock(progress,sendedSize,weakself.fileDownUpModel,key);
                    }
                    i++;
                }
                
                if (weakself.uploadProgressDBBlock) {
                    weakself.uploadProgressDBBlock(progress,sendedSize,weakself.fileDownUpModel);
                }
                
               
            };
            
            self.uploadSession.uploadFailedBlock = ^(NSString* errMessage,NSString *msgUUID){
            
                weakself.fileDownUpModel.downUpStatus = DownUpStatusFailure;
                
                [kCloudStorageDB updateCSDownUpFileStatusWithCSFileDownUpModel:weakself.fileDownUpModel];
              
                
                int i = 0;
                for (CSUploadFailedUIBlock faiureBlock in weakself.failureBlocksDict.allValues) {
                    
                    NSString *key = weakself.failureBlocksDict.allKeys[i];
                    if (faiureBlock) {
                        //一方面,所有的model都注册了,另一方面,有时候多个model公共一个task.
                        faiureBlock(errMessage,weakself.fileDownUpModel,key);
                    }
                    i++;
                }
                
                
                if (weakself.uploadFailedDBBlock) {
                    weakself.uploadFailedDBBlock (errMessage,weakself.fileDownUpModel);
                }
                
              

            };
            

        }else{
        
            //失败
            self.fileDownUpModel.downUpStatus = DownUpStatusFailure;
            
            [kCloudStorageDB updateCSDownUpFileStatusWithCSFileDownUpModel:self.fileDownUpModel];
            
            int i = 0;
            for (CSUploadFailedUIBlock faiureBlock in self.failureBlocksDict.allValues) {
                
                NSString *key = self.failureBlocksDict.allKeys[i];
                if (faiureBlock) {
                    //一方面,所有的model都注册了,另一方面,有时候多个model公共一个task.
                    faiureBlock(nil,self.fileDownUpModel,key);
                }
                i++;
            }
            
            if (self.uploadFailedDBBlock) {
                self.uploadFailedDBBlock (nil,self.fileDownUpModel);
            }
            
           
        }
        
        
        
        
    }];

}

- (void)addBlockToUIWithUUID:(NSString *)uuid withProcessBlock:(CSUploadProgressUIBlock)processBlock successBlock:(CSUploadSuccessUIBlock)successBlock failBlock:(CSUploadFailedUIBlock)failBlock
{
    [self.successBlocksDict setObject:successBlock forKey:uuid];
    [self.progressBlocksDict setObject:processBlock forKey:uuid];
    [self.failureBlocksDict setObject:failBlock forKey:uuid];
}

- (void)cancerUpload
{
    [self.uploadSession cancerUpload];
}
@end
