//
//  NvPreViewLiveWindow.m
//  SDKDemo
//
//  Created by 刘东旭 on 2018/9/25.
 //
//

#import "NvPreViewLiveWindow.h"
#import "NvsLiveWindow.h"
#import "NvTimelineUtils.h"
#import "NvWeakTimer.h"
#import "NvSDKUtils.h"

@interface NvPreViewLiveWindow ()<NvsStreamingContextDelegate>

@property (nonatomic, strong) NvsLiveWindow *livewindow;
@property (nonatomic, strong) NvsStreamingContext *context;
@property (nonatomic, strong) UIButton *closeButton;
@property (nonatomic, strong) UIButton *compileButton;
@property (nonatomic, strong) UIImageView *playImageView;
@property (nonatomic, strong) UISlider *slider;
@property (nonatomic, strong) NvsTimeline *timeline;
@property (nonatomic, strong) NvWeakTimer *timer;

@end

@implementation NvPreViewLiveWindow

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = UIColor.blackColor;
        self.context = [NvsStreamingContext sharedInstanceWithFlags:NvsStreamingContextFlag_Support4KEdit];
        self.context.delegate = self;
        self.livewindow = [[NvsLiveWindow alloc] initWithFrame:CGRectMake(0, 0, SCREANWIDTH, SCREANHEIGHT)];
        self.livewindow.center = self.center;
        [self addSubview:self.livewindow];
        
        self.closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.closeButton.frame = CGRectMake(13*SCREANSCALE, NV_STATUSBARHEIGHT, 37*SCREANSCALE, 37*SCREANSCALE);
        [self.closeButton setImage:[NvUtils imageWithName:@"Nvback"] forState:UIControlStateNormal];
        [self.closeButton addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:self.closeButton];
        
        self.compileButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.compileButton.frame = CGRectMake(SCREANWIDTH - 50*SCREANSCALE, NV_STATUSBARHEIGHT, 37*SCREANSCALE, 37*SCREANSCALE);
        [self.compileButton setImage:[NvUtils imageWithName:@"NvCompile"] forState:UIControlStateNormal];
        [self.compileButton addTarget:self action:@selector(compileClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:self.compileButton];
        
        self.playImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 64*SCREANSCALE, 64*SCREANSCALE)];
        self.playImageView.image = [NvUtils imageWithName:@"NvParticlePreviewPlay"];
        self.playImageView.center = self.center;
        self.playImageView.userInteractionEnabled = YES;
        [self.playImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(playOrStop:)]];
        [self addSubview:self.playImageView];
        
        self.slider = [[UISlider alloc]initWithFrame:CGRectMake(0, SCREANHEIGHT - INDICATOR - 95 * SCREANSCALE, SCREANWIDTH, 20)];
        [_slider setThumbImage:[NvUtils imageWithName:@"Nvslider"] forState:UIControlStateNormal];
        _slider.minimumValue = 0;
        _slider.maximumValue = 1;
        [_slider setMinimumTrackTintColor:UIColor.whiteColor];
        [_slider setMaximumTrackTintColor:UIColor.whiteColor];
        [_slider addTarget:self action:@selector(progressSliderValueChanged:) forControlEvents:(UIControlEventValueChanged)];
        [_slider addTarget:self action:@selector(progressSliderValueDidEnd:) forControlEvents:UIControlEventTouchUpInside];
        [_slider addTarget:self action:@selector(progressSliderValueDidEnd:) forControlEvents:UIControlEventTouchUpOutside];
        [self addSubview:self.slider];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
        [self.livewindow addGestureRecognizer:tap];
        
    }
    return self;
}

- (void)singleTap:(UITapGestureRecognizer *)gesture{
    if (self.playImageView.hidden == YES) {
        self.playImageView.hidden = NO;
        if (_timer) {
            [_timer invalidate];
            _timer = nil;
        }
        _timer = [NvWeakTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(hideControlPanel:) userInfo:nil repeats:NO dispatchQueue:dispatch_get_main_queue()];
    } else {
        if (_context.getStreamingEngineState == NvsStreamingEngineState_Playback) {
            [self pause];
        }else{
            [self play];
        }
    }
}

- (void)hideControlPanel:(NvWeakTimer *)timer{
    if (!_playImageView.hidden){
        _playImageView.hidden = YES;
    }
}

- (void)setModel:(NvEditMode)model {
    _model = model;
    if (self.model == NvEditMode16v9) {
        self.livewindow.frame = CGRectMake(0, 0, SCREANWIDTH, SCREANWIDTH * 9 / 16);
    } else {
        self.livewindow.frame = CGRectMake(0, 0, SCREANWIDTH, SCREANHEIGHT);
    }
    self.livewindow.center = self.center;
    self.timeline = [NvTimelineUtils createTimeline:model];
    [self.context connectTimeline:self.timeline withLiveWindow:self.livewindow];
    NvsVideoTrack *videoTrack = [self.timeline getVideoTrackByIndex:0];
    
    if (videoTrack == nil) {
        return;
    }
    
    for (int i = 0; i < self.pathArray.count; i++) {
        [videoTrack appendClip:self.pathArray[i]];
    }
     [_context seekTimeline:_timeline timestamp:0 videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:0];
}

- (void)backClick:(UIButton *)button {
    if ([self.delegate respondsToSelector:@selector(backClick)]) {
        [self.context stop];
        [self.delegate backClick];
    }
}

- (void)compileClick:(UIButton *)button {
    [self pause];
    if ([self.delegate respondsToSelector:@selector(compileClick:)]) {
        [self.delegate compileClick:self.timeline];
    }
}

- (void)progressSliderValueDidEnd:(UISlider *)slider{
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    self.playImageView.hidden = NO;
}

- (void)progressSliderValueChanged:(UISlider *)slider{
    [self seek:lround(slider.value * self.timeline.duration)];
}

- (void)play {
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    _timer = [NvWeakTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(hideControlPanel:) userInfo:nil repeats:NO dispatchQueue:dispatch_get_main_queue()];
    [self.context playbackTimeline:self.timeline startTime:[self.context getTimelineCurrentPosition:self.timeline] endTime:self.timeline.duration videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize preload:YES flags:0];
}

- (void)pause {
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    self.playImageView.hidden = NO;
    [self.context stop];
}

- (void)playOrStop:(UITapGestureRecognizer *)tap {
    if (self.context.getStreamingEngineState == NvsStreamingEngineState_Playback) {
        [self pause];
    }else{
        [self play];
    }
}

- (void)seek:(int64_t)pos {
    [self.context seekTimeline:self.timeline timestamp:pos videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:0];
}

- (void)didPlaybackTimelinePosition:(NvsTimeline *)timeline position:(int64_t)position {
    [self.slider setValue:(float)position / timeline.duration animated:YES];
}

/*!
 *  \brief 播放预先加载完成
 *  \param timeline 时间线
 */
- (void)didPlaybackPreloadingCompletion:(NvsTimeline *)timeline{
    [self didStreamingEngineStateChanged:self.context.getStreamingEngineState];
}

/*!
 *  \brief 播放停止
 *  \param timeline 时间线
 */
- (void)didPlaybackStopped:(NvsTimeline *)timeline {
    [self didStreamingEngineStateChanged:self.context.getStreamingEngineState];
}

/*!
 *  \brief 播放到结尾
 *  \param timeline 时间线
 */
- (void)didPlaybackEOF:(NvsTimeline *)timeline {
    [self seek:0];
    [self.slider setValue:0 animated:YES];
    [self didStreamingEngineStateChanged:self.context.getStreamingEngineState];
}

- (void)againConnection{
    if (![[NvSDKUtils getSDKContext] connectTimeline:_timeline withLiveWindow:_livewindow]) {
        NSLog(@"连接预览窗口失败！");
        return;
    }
    [NvSDKUtils getSDKContext].delegate = self;
    [self seek:[self.context getTimelineCurrentPosition:self.timeline]];
}

/*!
 *  \brief 生成视频文件进度
 *  \param timeline 时间线
 *  \param progress 进度值
 */
- (void)didCompileProgress:(NvsTimeline *)timeline progress:(int)progress {
    
}


/*!
 *  \brief 生成视频文件完成
 *  \param timeline 时间线
 *  \param isCanceled 中途取消导致生成完成。注：任何对引擎操作引起的停止生成均视为中途取消
 *  \since 1.6.0
 *  \sa didCompileFinished:
 */
- (void)didCompileCompleted:(NvsTimeline *)timeline isCanceled:(BOOL)isCanceled {
    
}

/*!
 *  \brief 生成视频文件失败
 *  \param timeline 时间线
 */
- (void)didCompileFailed:(NvsTimeline *)timeline {
    
}

/*!
 *  \brief 引擎状态改变
 *  \param state 引擎状态
 */
- (void)didStreamingEngineStateChanged:(NvsStreamingEngineState)state {
    if (state == NvsStreamingEngineState_Playback) {
        self.playImageView.image = [NvUtils imageWithName:@"NvParticlePreviewSuspend"];
    } else {
        self.playImageView.image = [NvUtils imageWithName:@"NvParticlePreviewPlay"];
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
