//
//  NvFileConvert.m
//  SDKDemo
//
//  Created by 刘东旭 on 2018/9/6.
 //
//

#import "NvFileConvert.h"
#include "NvcConvertor.h"
#import "NVHeader.h"

@interface NvFileConvert() <NvcConvertorDelegate>{
    NvcConvertor *mConvertor;
    struct SNvcOutputConfig config;
    dispatch_semaphore_t sem;
    NSFileManager *fm;
    NSString *tmpfilePath;
}

@property (nonatomic) void(^finishBlock)(BOOL);
@property (nonatomic) NSArray <NvRecordingInfo *>*files;
@property (nonatomic) NvRecordingInfo *nextFile;
@property (nonatomic) BOOL isAllFinish;

@end

@implementation NvFileConvert

- (void)dealloc {
    NSLog(@"%s",__func__);
}

- (instancetype)init {
    if (self = [super init]) {
        fm = [NSFileManager defaultManager];
        self.isAllFinish = YES;
        mConvertor = [[NvcConvertor alloc] init];
        mConvertor.delegate = self;
    }
    return self;
}

- (void)convertFiles:(NSArray <NvRecordingInfo *>*)files {
    self.files = [files copy];
    self.nextFile = self.files.firstObject;
}

- (void)startConvert {
    NvRecordingInfo *file = self.nextFile;
    
    if (![fm fileExistsAtPath:CONVERTPATH]) {
        [fm createDirectoryAtPath:CONVERTPATH withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *last;
    if (file.asset!=nil) {
        last = [NSString stringWithFormat:@"%@.mp4",[NvUtils currentDateAndTime]];
    } else {
        last = [file.recordingPath lastPathComponent];
    }
    
    tmpfilePath = [CONVERTPATH stringByAppendingPathComponent:last];
    [mConvertor close];
    
    config.from = file.trimIn*1.0/NV_TIME_BASE;
    config.to = file.trimOut*1.0/NV_TIME_BASE;
    config.dataRate = 0;
    config.videoResolution = NvcOutputVideoResolution_NotResize;
    
    float nTmp = config.from;
    config.from = config.to;
    config.to = nTmp;
    
    __block NSInteger ret = 0;
    if (file.asset != nil) {
        [[PHImageManager defaultManager] requestAVAssetForVideo:file.asset options:nil resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
            
            ret = [self->mConvertor open:((AVURLAsset *)asset).URL.absoluteString outputFile:self->tmpfilePath setting:&self->config];
            if(ret != NVC_NOERROR){
                NSString* error = nil;
                if(ret == NVC_E_INVALID_POINTER)
                    error = @"无效指针";
                else if(ret == NVC_E_INVALID_PARAMETER)
                    error = @"无效参数";
                else if(ret == NVC_E_NO_VIDEO_STREAM)
                    error = @"输入文件不存在视频流";
                else if(ret == NVC_E_CONVERTOR_IS_OPENED)
                    error = @"当前转码器已经打开";
                else if(ret == NVC_E_CONVERTOR_IS_STARTED)
                    error = @"正在转码";
                
                NSLog(@"%@",error);
                return;
            }
            
            [self->mConvertor start];
        }];
    } else {
        ret = [mConvertor open:file.recordingPath outputFile:tmpfilePath setting:&config];
        if(ret != NVC_NOERROR){
            NSString* error = nil;
            if(ret == NVC_E_INVALID_POINTER)
                error = @"无效指针";
            else if(ret == NVC_E_INVALID_PARAMETER)
                error = @"无效参数";
            else if(ret == NVC_E_NO_VIDEO_STREAM)
                error = @"输入文件不存在视频流";
            else if(ret == NVC_E_CONVERTOR_IS_OPENED)
                error = @"当前转码器已经打开";
            else if(ret == NVC_E_CONVERTOR_IS_STARTED)
                error = @"正在转码";
            
            NSLog(@"%@",error);
            return;
        }
        
        [mConvertor start];
    }
    
    
}

- (void)cancel {
    NSLog(@"convert cancel");
    [mConvertor cancel];
    [mConvertor close];
    mConvertor.delegate = nil;
    mConvertor = nil;
    self.files = nil;
}

- (void)finishBlock:(void(^)(BOOL isFinish))finishBlock {
    self.finishBlock = finishBlock;
}

/*!
 *  \brief 转码完成
 */
- (void)convertFinished {
    self.nextFile.convertPath = tmpfilePath;
    if (self.files.lastObject == self.nextFile) {
        [mConvertor stop];
        self.finishBlock(self.isAllFinish);
    } else {
        self.nextFile = [self.files objectAtIndex:[self.files indexOfObject:self.nextFile]+1];
        [self startConvert];
    }
}

/*!
 *  \brief 转码失败
 *  \param error 错误值
 */
- (void)convertFaild:(NSError *)error {
    NSLog(@"转码失败");
    self.isAllFinish = NO;
    if (self.files.lastObject == self.nextFile) {
        [mConvertor stop];
        self.finishBlock(self.isAllFinish);
    } else {

        self.nextFile = [self.files objectAtIndex:[self.files indexOfObject:self.nextFile]+1];
    }
}

- (void)convertProgress:(int)progress {
#ifdef DEBUG
    NSLog(@"----->%d",progress);
#endif
}

@end
