//
//  PlayerViewController+downloadFile.m
//  隐私保护
//
//  Created by xd h on 2024/1/9.
//

#import "PlayerViewController+downloadFile.h"
#import "cachesFileManager.h"
#import "downloadManager.h"

@implementation PlayerViewController (downloadFile)
- (void)begindownloadFileFun:(NSNotification *)notification
{
    self.curDownloadFileModel = [notification object];
    
    if(!self.curDownloadFileModel
       || ![self.curDownloadFileModel isKindOfClass:[couldPhoneFileModel class]]){
        return;
    }
    
    [self ApplyDownloadFileFun];
}

#pragma mark 申请下载缩略图
- (void)ApplyDownloadFileFun
{
    
    self.downloadFileTaskUid = [iTools getTaskUidStr];
 
    if([self.downloadFileTaskUid isEqualToString:self.backupsTaskUid]
       ||[self.downloadFileTaskUid isEqualToString:self.taskUid])
    {//重新生成taskUid
        [self ApplyDownloadFileFun];
        return;
    }
    
    NSString *fileName = [self.curDownloadFileModel getFileNameFun];
    NSString*pathStr = [cachesFileManager getFilePathWithName:fileName type:DownLoadFileType];
    long didDownloadBytes = 0;
    
    NSFileManager *manager0 = [NSFileManager defaultManager];
    if([manager0 fileExistsAtPath:pathStr]) {
        NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:pathStr]; // 创建文件句柄
        if (fileHandle) {
            didDownloadBytes = [fileHandle seekToEndOfFile];
            // 关闭文件句柄
            [fileHandle closeFile];
        }
    }
    
    NSString * commandStr = [RCCommandHelp applyForDownloadFileBy:self.downloadFileTaskUid withFilePath:self.curDownloadFileModel.path withPosition:didDownloadBytes];
    [self.commandChannelManager rc_sendData:commandStr];
}

- (void)downloadFileFunServiceResponseFun:(NSData *)fileData  with:(BOOL)isDownloadDone
{
    if(isDownloadDone){
        [self handleDownloadDoneFun];
        return;
    }
    
    NSString *fileName = [self.curDownloadFileModel getFileNameFun];
        
    NSString*pathStr = [cachesFileManager getFilePathWithName:fileName type:DownLoadFileType];
    
    NSFileManager *manager0 = [NSFileManager defaultManager];
    long long endOfFile = 0;
    
    if(![manager0 fileExistsAtPath:pathStr]) {
        [cachesFileManager getFileNameWithContent:fileData fileName:fileName type:DownLoadFileType];
    }
    else{
        NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:pathStr]; // 创建文件句柄
        if (fileHandle) {
            endOfFile = [fileHandle seekToEndOfFile];
            if (endOfFile >=  0) {
                if(endOfFile == self.curDownloadFileModel.didDownloadBytes){
                    [fileHandle writeData:fileData];
                }
            }
            
            endOfFile = [fileHandle seekToEndOfFile];
            // 关闭文件句柄
            [fileHandle closeFile];
        }
    }
    
    long didDownloadBytes = fileData.length;
    if(endOfFile > 0){
        didDownloadBytes = endOfFile;
    }
    
    self.curDownloadFileModel.didDownloadBytes = didDownloadBytes;
   

    
//    if(isDownloadDone || endOfFile == self.curDownloadFileModel.length){
//        [self handleDownloadDoneFun];
//    }
//    else
    {//获取下一片
        
        [[downloadManager shareInstance] DownloadFileChangeingOneFileFun];
        
        if([downloadManager shareInstance].isSuspendType){
            return;
        }
        
        NSString * commandStr = [RCCommandHelp applyForDownloadFileBy:self.downloadFileTaskUid withFilePath:self.curDownloadFileModel.path withPosition:didDownloadBytes];
        [self.commandChannelManager rc_sendData:commandStr];
    }
    
}

- (void)handleDownloadDoneFun
{
    if([self.curDownloadFileModel.fileType isEqualToString:@".jpg"]){
        NSString *fileName = [self.curDownloadFileModel getFileNameFun];
        NSString*pathStr = [cachesFileManager getFilePathWithName:fileName type:DownLoadFileType];
        UIImage *image = [UIImage imageWithContentsOfFile:pathStr];
        
        if(image){
            [self loadImageFinished:image];
        }
        else{
            [cachesFileManager removeItemAtPath:fileName type:DownLoadFileType error:nil];
            [[downloadManager shareInstance] DownloadFileFailOneFileFun];
        }
    }
    else if([self.curDownloadFileModel.fileType isEqualToString:@"video"]){
        [self loadVideoFinished];
    }
    
}


- (void)loadImageFinished:(UIImage *)image
{
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
         //写入图片到相册
         PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
            
     } completionHandler:^(BOOL success, NSError * _Nullable error) {
         //NSLog(@"success = %d, error = %@", success, error);
         if (success) {
             HLog(@"已将图片保存至相册");
             NSString *fileName = [self.curDownloadFileModel getFileNameFun];
             [cachesFileManager removeItemAtPath:fileName type:DownLoadFileType error:nil];
             
         } else {
             HLog(@"未能将图片保存至相册");
         }
         
         [[downloadManager shareInstance] DownloadFileDoneOneFileFun];
    }];
}

- (void)loadVideoFinished
{
    NSString *fileName = [self.curDownloadFileModel getFileNameFun];
    NSString*pathStr = [cachesFileManager getFilePathWithName:fileName type:DownLoadFileType];
    
    PHPhotoLibrary *photoLibrary = [PHPhotoLibrary sharedPhotoLibrary];
    [photoLibrary performChanges:^{
        [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:[NSURL
    fileURLWithPath:pathStr]];
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        if (success) {
            HLog(@"已将视频保存至相册");
            //NSString *fileName = [self.curDownloadFileModel getFileNameFun];
            [cachesFileManager removeItemAtPath:fileName type:DownLoadFileType error:nil];
            
        } else {
            HLog(@"未能将视频保存至相册");
        }
        
        [[downloadManager shareInstance] DownloadFileDoneOneFileFun];
    }];
}
@end
