//
//  NvParEditViewController.m
//  SDKDemo
//
//  Created by ms20180425 on 2018/9/26.
 //
//

#import "NvParEditViewController.h"
#import "NvsParticleSystemContext.h"
#import "stMobileDetected.h"
#import "NvTimelineUtils.h"
#import "MSSysAlertUtil.h"
#import "NvEffectWrapper.h"
#import "NvParticleThumbnail.h"
#import "NvFilterCell.h"
#import "NvFilterItem.h"
#import "NvCanvasView.h"
#import "NvCompileViewController.h"
#import "NvParCaptureViewController.h"
#import "NvSDKUtils.h"
#import "NvAssetManager.h"

@interface NvParEditViewController ()<NvsStreamingContextDelegate,UICollectionViewDelegate,UICollectionViewDataSource,NvCanvasViewDelegate,NvParticleThumbnailDelegate,NvCompileViewControllerDelegate>

//头视图
@property (nonatomic, strong) UIView *headerView; //最外层
@property (nonatomic, strong) UIButton *backBtn;//退出
@property (nonatomic, strong) UIButton *playBtn;//播放按钮
@property (nonatomic, strong) UIButton *compileBtn;//生成按钮

//缩略图控件
//@property (nonatomic, strong) NvEffectWrapper *effectWrapper;
@property (nonatomic, strong) NvParticleThumbnail *effectWrapper;
//撤销
@property (nonatomic, strong) UIButton *undoBtn;

//粒子视图
@property (nonatomic, strong) UIView *particlePanelView;//最外层
@property (nonatomic, strong) UIView *particleHeaderView;  // 速率，强度的面板视图
@property (nonatomic, strong) UISlider *filterStrengthSlider;//滤镜强度
@property (nonatomic, strong) UILabel *filterStrengthLabel;//强度
@property (nonatomic, strong) UISlider *filterSpeeadSlider;//滤镜速率
@property (nonatomic, strong) UILabel *filterSpeeadLabel;//速率
@property (nonatomic, strong) UICollectionView *particleCollectionView;//粒子特效滑动视图
@property (nonatomic, strong) NSMutableArray *graffitiFxArray;        //涂鸦特效数组

//livewindow的外层view
@property (nonatomic, strong) UIView *liveWindowView;
@property (nonatomic, strong) NvsLiveWindow *liveWindow;

@property (nonatomic, strong) NvCanvasView *canvasView;//画布

//-----------------逻辑相关----------------//
@property (nonatomic, strong) NvFilterItem *currentItem; //当前粒子特效
@property (nonatomic, assign) int64_t startInpoint;      //裁入点时间
@property (nonatomic, strong) NSMutableArray *particleFxArray;//添加到时间线上的粒子特效
@property (nonatomic, strong) NvParticleInfoModel *currentInfoModel;  //当前时间线上的粒子特效
@property (nonatomic, strong) NvsTimelineVideoFx *timelineVideo; //当前时间线特效
@property (nonatomic, strong) NSString *compileFilePath;//生成路径

//-----------------sdk相关----------------//
@property (nonatomic, strong) NvsStreamingContext *streamingContext;
@property (nonatomic, strong) NvAssetManager *assetManager;//素材管理
@property (nonatomic, strong) NvsCaptureVideoFx *videoFx;  //粒子特效
@property (nonatomic, strong) NvsParticleSystemContext *particleContext;//粒子上下文
@property (nonatomic, strong) stMobileDetected *stMobileDtected;//粒子相关
@property (nonatomic, strong) NvsTimeline *timeline;//当前timeline

@end

@implementation NvParEditViewController

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"%s",__func__);
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NvSDKUtils getSDKContext] stop];
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.graffitiFxArray = [NSMutableArray array];
    self.particleFxArray = [NSMutableArray array];
    self.streamingContext = [NvSDKUtils getSDKContext];
    self.streamingContext.delegate = self;
    [self addParticleArray];
    [self addSubViews];
    [self initTimeline];
    [self addThumbnail];
    [self addParticleView];
    [self addObservers];
    // Do any additional setup after loading the view.
}

#pragma mark 给粒子视图的数组添加数据
- (void)addParticleArray{
    self.assetManager = [NvAssetManager sharedInstance];
    
    NvFilterItem *item = [NvFilterItem new];
    item.displayName = @"无";
    item.cover = @"NvsFilterNone";
    item.selected = NO;
    item.isParticle = YES;
    [self.graffitiFxArray addObject:item];
    
    NSArray *temporaryArray1 = [self.assetManager getUsableAssets:ASSET_PARTICLE aspectRatio:AspectRatio_All categoryId:4];
    for (NvAsset *asset in temporaryArray1) {
        if (asset.downloadStatus == DownloadStatusDecompressingFailed) {
            continue;
        }
        NvFilterItem *item = [NvFilterItem new];
        item.packID = asset.uuid;
        item.displayName = asset.name;
        item.cover = [asset.coverUrl absoluteString];
        item.categoryId = asset.categoryId;
        item.parser = asset.parser;
        item.color = asset.color;
        item.isParticle = YES;
        [self.graffitiFxArray addObject:item];
    }
}


#pragma mark 添加子视图
- (void)addSubViews{
    self.headerView = [[UIView alloc]init];
    self.headerView.backgroundColor = UIColor.blackColor;
    [self.view addSubview:self.headerView];
    
    self.backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backBtn addTarget:self action:@selector(backBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.backBtn setImage:[NvUtils imageWithName:@"Nvback"] forState:UIControlStateNormal];
    [self.headerView addSubview:self.backBtn];
    
    self.playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.playBtn setImage:[NvUtils imageWithName:@"NvParticlePlay"] forState:UIControlStateNormal];
    [self.playBtn setImage:[NvUtils imageWithName:@"NvParticleSuspend"] forState:UIControlStateSelected];
    [self.playBtn addTarget:self action:@selector(playBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:self.playBtn];
    
    self.compileBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.compileBtn setTitle:@"生成" forState:UIControlStateNormal];
    [self.compileBtn addTarget:self action:@selector(compileBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.compileBtn setTitleColor:[UIColor nv_colorWithHexRGB:@"#4A90E2"] forState:UIControlStateNormal];
    self.compileBtn.titleLabel.font = [UIFont systemFontOfSize:18 * SCREANSCALE];
    [self.headerView addSubview:self.compileBtn];
    
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.offset(NV_NAV_BAR_HEIGHT + NV_STATUSBARHEIGHT);
    }];
    
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.headerView.mas_left).offset(13 * SCREANSCALE);
        make.bottom.equalTo(self.headerView.mas_bottom).offset(-10 * SCREANSCALE);
        make.width.offset(30 * SCREANSCALE);
        make.height.offset(30 * SCREANSCALE);
    }];
    
    [self.playBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.headerView.mas_centerX);
        make.centerY.equalTo(self.backBtn.mas_centerY);
        make.width.offset(30 * SCREANSCALE);
        make.height.offset(30 * SCREANSCALE);
    }];
    
    [self.compileBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.headerView.mas_right).offset(- 13 * SCREANSCALE);
        make.centerY.equalTo(self.backBtn.mas_centerY);
        make.width.offset(50 * SCREANSCALE);
        make.height.offset(30 * SCREANSCALE);
    }];
    
    self.liveWindowView = [[UIView alloc]init];
    [self.view addSubview:self.liveWindowView];
    [self.liveWindowView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headerView.mas_bottom);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.offset(400 * SCREANSCALE);
    }];
    
    self.liveWindow = [[NvsLiveWindow alloc]init];
    [self.liveWindowView addSubview:self.liveWindow];
    
    
}

#pragma mark 创建timeline，绘制livewindow
- (void)initTimeline{
    [self.liveWindow mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.liveWindowView.mas_centerX);
        make.centerY.equalTo(self.liveWindowView.mas_centerY);
        if (self.editMode == NvEditMode16v9) {
            make.width.offset(SCREANWIDTH);
            make.height.offset(SCREANWIDTH * 9 /16);
        }else{
            make.width.offset(400 * SCREANSCALE * 9 / 16);
            make.height.equalTo(self.liveWindowView.mas_height);
        }
    }];
    
    self.canvasView = [[NvCanvasView alloc]init];
    self.canvasView.delegate = self;
    [self.liveWindow addSubview:self.canvasView];
    [self.canvasView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.liveWindow);
        make.right.equalTo(self.liveWindow);
        make.top.equalTo(self.liveWindow);
        make.bottom.equalTo(self.liveWindow);
    }];
    
    self.timeline = [NvTimelineUtils createTimeline:self.editMode];
    [self.streamingContext connectTimeline:self.timeline withLiveWindow:self.liveWindow];
    NvsVideoTrack *videoTrack = [self.timeline getVideoTrackByIndex:0];
    
    if (videoTrack == nil) {
        return;
    }
    
    for (int i = 0 ; i < self.selectAssets.count; i++) {
        NvAlbumAsset *asset = self.selectAssets[i];
        [videoTrack appendClip:asset.asset.localIdentifier];
    }
    [_streamingContext seekTimeline:_timeline timestamp:0 videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:0];
}

#pragma mark 添加缩略图控件
- (void)addThumbnail{
    self.effectWrapper = [[NvParticleThumbnail alloc]init];
    self.effectWrapper.delegate = self;
    [self.view addSubview:self.effectWrapper];
    [self.effectWrapper mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.liveWindowView.mas_bottom).offset(10 * SCREANSCALE);
        make.left.equalTo(self.view.mas_left).offset(13 * SCREANSCALE);
        make.right.equalTo(self.view.mas_right).offset(-13 * SCREANSCALE);
        make.height.offset(30 * SCREANSCALE);
    }];
    self.effectWrapper.sequenceView.descArray = [NvTimelineUtils getThumbnailSequenceDescArray:self.timeline];
    self.effectWrapper.sequenceView.pointsPerMicrosecond = (SCREANWIDTH - 26 * SCREANSCALE)/self.timeline.duration;
    self.effectWrapper.colorBarView.timelineDuration = self.timeline.duration;
    
    UILabel *tipLabel = [[UILabel alloc]init];
    tipLabel.text = @"选择位置后，在画面上涂画";
    tipLabel.font = [UIFont systemFontOfSize:12 * SCREANSCALE];
    tipLabel.textColor = [UIColor nv_colorWithHexARGB:@"#CCFFFFFF"];
    [self.view addSubview:tipLabel];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.effectWrapper.mas_bottom).offset(17 * SCREANSCALE);
        make.left.equalTo(self.effectWrapper.mas_left);
    }];
    
    self.undoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.undoBtn addTarget:self action:@selector(undoBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.undoBtn setImage:[NvUtils imageWithName:@"NvParticleUndo"] forState:UIControlStateNormal];
    [self.view addSubview:self.undoBtn];
    [self.undoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(tipLabel.mas_centerY);
        make.right.equalTo(self.effectWrapper.mas_right);
    }];
}

#pragma mark 添加粒子特效滚动视图
- (void)addParticleView{
    _particlePanelView = [[UIView alloc] init];
    _particlePanelView.backgroundColor = [UIColor nv_colorWithHexARGB:@"#99000000"];
    [self.view addSubview:_particlePanelView];
    [_particlePanelView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.offset(97 * SCREANSCALE + INDICATOR);
    }];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(58*SCREANSCALE, 70*SCREANSCALE);
    layout.minimumLineSpacing = 10*SCREANSCALE;
    layout.minimumInteritemSpacing = 0;
    layout.sectionInset = UIEdgeInsetsMake(0, 16*SCREANSCALE, 0, 0);
    _particleCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    _particleCollectionView.delegate = self;
    _particleCollectionView.dataSource = self;
    _particleCollectionView.backgroundColor = [UIColor clearColor];
    _particleCollectionView.showsHorizontalScrollIndicator = NO;
    [_particlePanelView addSubview:_particleCollectionView];
    [_particleCollectionView registerClass:[NvFilterCell class] forCellWithReuseIdentifier:@"NvFilterCell"];
    [_particleCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.particlePanelView.mas_top);
        make.bottom.equalTo(self.particlePanelView.mas_bottom);
        make.left.equalTo(self.particlePanelView.mas_left);
        make.right.equalTo(self.particlePanelView.mas_right);
    }];
    
    _particleHeaderView = [[UIView alloc] init];
    _particleHeaderView.hidden = YES;
    _particleHeaderView.backgroundColor = UIColor.blackColor;
    [_particlePanelView addSubview:_particleHeaderView];
    [_particleHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.particlePanelView);
        make.bottom.equalTo(self.particlePanelView);
        make.left.equalTo(self.particlePanelView);
        make.right.equalTo(self.particlePanelView);
    }];
    
    self.filterSpeeadLabel = [[UILabel alloc]initWithFrame:CGRectMake(13 * SCREANSCALE, 17 * SCREANSCALE, 28 * SCREANSCALE, 20 * SCREANSCALE)];;
    _filterSpeeadLabel.text = @"速率";
    _filterSpeeadLabel.font = [UIFont systemFontOfSize:13 * SCREANSCALE];
    _filterSpeeadLabel.textColor = UIColor.whiteColor;
    [_filterSpeeadLabel sizeToFit];
    [_particleHeaderView addSubview:_filterSpeeadLabel];
    
    self.filterSpeeadSlider = [[UISlider alloc]initWithFrame:CGRectMake(55 * SCREANSCALE, 24 * SCREANSCALE, 308 * SCREANSCALE, 10 * SCREANSCALE)];
    [self.filterSpeeadSlider setMinimumValue:0.1];
    [self.filterSpeeadSlider setMaximumValue:6.0];
    self.filterSpeeadSlider.value = 1;
    self.filterSpeeadSlider.minimumTrackTintColor = [UIColor whiteColor];
    self.filterSpeeadSlider.maximumTrackTintColor = [UIColor whiteColor];
    [self.filterSpeeadSlider setThumbImage:[NvUtils imageWithName:@"Nvslider"] forState:UIControlStateNormal];
    [self.filterSpeeadSlider addTarget:self action:@selector(sliderValueChangedFX:) forControlEvents:UIControlEventValueChanged];
    [_particleHeaderView addSubview:_filterSpeeadSlider];
    
    self.filterStrengthLabel = [[UILabel alloc]initWithFrame:CGRectMake(13 * SCREANSCALE, 43 * SCREANSCALE, 28 * SCREANSCALE, 20 * SCREANSCALE)];;
    _filterStrengthLabel.text = @"强度";
    _filterStrengthLabel.font = [UIFont systemFontOfSize:13 * SCREANSCALE];
    _filterStrengthLabel.textColor = UIColor.whiteColor;
    [_filterStrengthLabel sizeToFit];
    [_particleHeaderView addSubview:_filterStrengthLabel];
    
    self.filterStrengthSlider = [[UISlider alloc]initWithFrame:CGRectMake(55 * SCREANSCALE, 50 * SCREANSCALE, 308 * SCREANSCALE, 10 * SCREANSCALE)];
    [self.filterStrengthSlider setMinimumValue:0.1];
    [self.filterStrengthSlider setMaximumValue:6.0];
    self.filterStrengthSlider.value = 1;
    self.filterStrengthSlider.enabled = YES;
    self.filterStrengthSlider.minimumTrackTintColor = [UIColor whiteColor];
    self.filterStrengthSlider.maximumTrackTintColor = [UIColor whiteColor];
    [self.filterStrengthSlider setThumbImage:[NvUtils imageWithName:@"Nvslider"] forState:UIControlStateNormal];
    [self.filterStrengthSlider addTarget:self action:@selector(sliderValueChangedFX:) forControlEvents:UIControlEventValueChanged];
    [_particleHeaderView addSubview:_filterStrengthSlider];
}

#pragma mark 蒙层——用于收起滤镜强度、速度强度调节控件
- (void)addMontmorillonite{
    UIButton *MontmorilloniteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    MontmorilloniteBtn.backgroundColor = UIColor.clearColor;
    [MontmorilloniteBtn addTarget:self action:@selector(MontmorilloniteBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:MontmorilloniteBtn];
    [MontmorilloniteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.particlePanelView.mas_top);
    }];
}

- (void)MontmorilloniteBtnClick:(UIButton *)sender{
    [sender removeFromSuperview];
    self.particleHeaderView.hidden = YES;
}

#pragma mark 滤镜强度、速度强度调节
- (void)sliderValueChangedFX:(UISlider *)slider{
    NSArray* emitter = [self.currentItem.parser getParticlePartitionEmitter:0];
    if ([slider isEqual:self.filterStrengthSlider]) {
        for (int i = 0; i < emitter.count; i++){
           [self.particleContext SetEmitterParticleSizeGain:emitter[i] emitterGain:slider.value];
        }
    }
    if ([slider isEqual:self.filterSpeeadSlider]) {
        for (int i = 0; i < emitter.count; i++){
            [self.particleContext setEmitterRateGain:emitter[i] emitterGain:slider.value];
        }
    }
}

#pragma mark 播放点击事件
- (void)playBtnClick:(UIButton *)sender{
    if (sender.selected) {
        [self.streamingContext stop];
    }else{
        [self.streamingContext playbackTimeline:self.timeline startTime:[self.streamingContext getTimelineCurrentPosition:self.timeline] endTime:self.timeline.duration videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize preload:YES flags:0];
    }
}

#pragma mark 生成按钮点击事件
- (void)compileBtnClick:(UIButton *)sender{
    _compileFilePath = [VIDEO_PATH(@"Compile") stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4", [NvUtils currentDateAndTime]]];
    NvCompileViewController *compileViewController = [NvCompileViewController new];
    compileViewController.delegate = self;
    compileViewController.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [self presentViewController:compileViewController animated:NO completion:nil];
    [compileViewController compileTimeline:_timeline outputPath:_compileFilePath];
}

#pragma mark 退出
- (void)backBtnClick:(UIButton *)sender{
    [self.streamingContext stop];
    int index = (int)[[self.navigationController viewControllers]indexOfObject:self];
    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:(index -2)] animated:YES];
}

- (void)connectLiveWindow {
    if (!self.timeline) {
        return;
    }
    
    [self connectTimeline];
    [self.streamingContext seekTimeline:self.timeline timestamp:[self.streamingContext getTimelineCurrentPosition:self.timeline] videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:0];
}

- (void)connectTimeline{
    if (![self.streamingContext connectTimeline:self.timeline withLiveWindow:_liveWindow]) {
        NSLog(@"连接预览窗口失败！");
        return;
    }
    self.streamingContext.delegate = self;
}


#pragma mark - NvCompileViewControllerDelegate
- (void)compileFinished:(BOOL)needDelete {
    [self connectLiveWindow];
    if (needDelete) {
        [[NSFileManager defaultManager] removeItemAtPath:self.compileFilePath error:nil];
    } else {
        UISaveVideoAtPathToSavedPhotosAlbum(self.compileFilePath, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
    }
}

#pragma mark 将拍摄的视频保存到本地相册
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"打包成功" message:@"已保存至相册" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
}

#pragma mark 撤销按钮点击事件
- (void)undoBtnClick:(UIButton *)sender{
    if (self.particleFxArray.count != 0 && self.particleFxArray != nil) {
        NvParticleInfoModel *infoModel = [self.particleFxArray lastObject];
        [self seek:infoModel.inPoint];
        self.effectWrapper.sliderView.value = (float)infoModel.inPoint/_timeline.duration;
        self.startInpoint = infoModel.inPoint;
        [self.particleFxArray removeLastObject];
        [self updateColorBarView:self.particleFxArray];
        NvsTimelineVideoFx *lastFx = [self.timeline getLastTimelineVideoFx];
        [self.timeline removeTimelineVideoFx:lastFx];
    }
}

#pragma mark seek画面
- (void)seek:(int64_t)pos {
    [self.streamingContext seekTimeline:self.timeline timestamp:pos videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:0];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.graffitiFxArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NvFilterCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NvFilterCell" forIndexPath:indexPath];
    [cell renderCellWithItem:self.graffitiFxArray[indexPath.item]];
    return cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    for (NvFilterItem *model in self.graffitiFxArray) {
        model.selected = NO;
    }
    NvFilterItem *model = self.graffitiFxArray[indexPath.item];
    model.selected = YES;
    
    if (indexPath.item != 0) {
        if (self.currentItem) {
            if ([self.currentItem isEqual:model]) {
                self.particleHeaderView.hidden = NO;
                [self addMontmorillonite];
                return;
            }else{
                self.filterSpeeadSlider.value = 1;
                self.filterStrengthSlider.value = 1;
            }
        }
    }
    self.currentItem = model;
    [collectionView reloadData];
    
}

#pragma mark NvCanvasViewDelegate
//此次触摸开始,创建出粒子特效对象,加入到数组中
- (void)canvasViewState:(CGPoint)statePoint{
    NSLog(@"%lld,%lld",self.startInpoint,self.timeline.duration);
    if (!self.currentItem) {
        return;
    }
    if (self.startInpoint < self.timeline.duration) {
        self.effectWrapper.colorBarView.timelineStartPosition = self.startInpoint;
        float posX = self.effectWrapper.sliderView.value * (SCREANWIDTH - 26 * SCREANSCALE);
        [self.effectWrapper.colorBarView addBar:posX width:0 color:self.currentItem.color fxUuid:self.currentItem.packID];
        
        NvParticleInfoModel *infoModel = [NvParticleInfoModel new];
        infoModel.uuid = self.currentItem.packID;
        infoModel.name = self.currentItem.displayName;
        infoModel.inPoint = self.startInpoint;
        infoModel.color = self.currentItem.color;
        infoModel.particleRateValue = self.filterSpeeadSlider.value;
        infoModel.particleSizeValue = self.filterStrengthSlider.value;
        infoModel.emitterName = [NSMutableArray arrayWithArray:[self.currentItem.parser getParticlePartitionEmitter:0]];
        self.currentInfoModel = infoModel;
        [self.particleFxArray addObject:infoModel];
        self.timelineVideo = [self.timeline addPackagedTimelineVideoFx:self.startInpoint duration:_timeline.duration videoFxPackageId:infoModel.uuid];
        [_timelineVideo setFloatVal:@"Tail Fading Duration" val:0.5];
    }
}

//此次触摸时间的时长
- (void)canvasViewDuration:(int64_t)duration withPosition:(CGPoint)position{
    if (!self.currentItem) {
        return;
    }
    if ((duration + self.startInpoint) < self.timeline.duration) {
        [self seek:self.startInpoint + duration];
        self.effectWrapper.sliderView.value = (float)(self.startInpoint + duration)/_timeline.duration;
        [self setParser:self.currentItem.parser withPoint:position withDuration:duration];
    }
}

//此次触摸结束
- (void)canvasViewEnd:(int64_t)duration{
    if (!self.currentItem) {
        return;
    }
    if ((duration + self.startInpoint) < self.timeline.duration) {
        self.currentInfoModel.outPoint = self.startInpoint + duration;
        self.startInpoint = self.currentInfoModel.outPoint;
    }else{
         self.currentInfoModel.outPoint = self.timeline.duration;
        self.startInpoint = self.timeline.duration;
    }
    [self.timelineVideo changeOutPoint:[_streamingContext getTimelineCurrentPosition:_timeline]];
    [self updateColorBarView:self.particleFxArray];
}

#pragma mark 在livewindow上添加粒子特效
- (void)setParser:(NvsAssetPackageParticleDescParser *)parser withPoint:(CGPoint)point withDuration:(int64_t)duration{
    NvsParticleSystemContext *particleContext = [self.timelineVideo getParticleSystemContext];
    NSArray* emitters = [parser getParticlePartitionEmitter:0];
    CGPoint p1 = [_liveWindow mapViewToCanonical:point];
    CGPoint p = [_timelineVideo mapPointFromCanonicalToParticleSystem:p1];
    
    for(int i = 0; i < emitters.count; i++){
        
        [particleContext appendPositionToEmitterPositionCurve:emitters[i] curveTime:duration/1000000.0 emitterPositionX:p.x emitterPositionY:p.y];
        [particleContext SetEmitterParticleSizeGain:emitters[i] emitterGain:self.currentInfoModel.particleSizeValue];
        [particleContext setEmitterRateGain:emitters[i] emitterGain:self.currentInfoModel.particleRateValue];
    }
    self.effectWrapper.colorBarView.timelineCurrentPosition = self.effectWrapper.colorBarView.timelineStartPosition + duration;
    [self.effectWrapper.colorBarView updateLastBar:NO];
}

#pragma mark 在缩略图添加对应的视图
- (void)updateColorBarView:(NSMutableArray *)fxNewArray {
    [self.effectWrapper.colorBarView clearCurrentArray];
    NSMutableArray *colorArray = [NSMutableArray array];
    for (int i = 0; i < fxNewArray.count; i++) {
        NvParticleInfoModel *info = [fxNewArray objectAtIndex:i];
        int64_t inPoint = info.inPoint;
        int64_t outPoint = info.outPoint;
        NSString *fxUUID = info.uuid;
        [self.effectWrapper.colorBarView addToCurrentArray:fxUUID inPoint:inPoint outPoint:outPoint];
        [colorArray addObject:info.color];
    }
    [self.effectWrapper.colorBarView updateSubviewsByCurrentArray:NO withColor:colorArray];
}

#pragma mark NvEffectWrapperDelegate
- (void)sliderValueChanged:(UISlider *)slider{
    self.startInpoint = lround(slider.value * self.timeline.duration);
    [self seek:lround(slider.value * self.timeline.duration)];
}

#pragma mark NvsStreamingContextDelegate
//播放中
- (void)didPlaybackTimelinePosition:(NvsTimeline *)timeline position:(int64_t)position {
    self.effectWrapper.sliderView.value = (float)position/timeline.duration;
    self.startInpoint = position;
}

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

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

/*!
 *  \brief 播放到结尾
 *  \param timeline 时间线
 */
- (void)didPlaybackEOF:(NvsTimeline *)timeline {
    self.startInpoint = 0;
    self.effectWrapper.sliderView.value = 0;
    [self seek:0];
    [self didStreamingEngineStateChanged:self.streamingContext.getStreamingEngineState];
}

- (void)didStreamingEngineStateChanged:(NvsStreamingEngineState)state {
    if (state == NvsStreamingEngineState_Playback) {
        self.playBtn.selected = YES;
    } else {
        self.playBtn.selected = NO;
    }
}

#pragma mark 注册应用前台后台通知事件
- (void)addObservers {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
}

// 应用进入后台，停止采集
- (void)applicationWillResignActive:(NSNotification*)notification {
    if ([_streamingContext getStreamingEngineState] == NvsStreamingEngineState_Playback) {
        [_streamingContext stop];
    }
}

// 应用进入前台，开始采集
- (void)applicationDidBecomeActive:(NSNotification*)notification {
//    if ([_streamingContext getStreamingEngineState] == NvsStreamingEngineState_Stopped) {
//        [_streamingContext stop];
//        [self.streamingContext playbackTimeline:self.timeline startTime:[self.streamingContext getTimelineCurrentPosition:self.timeline] endTime:self.timeline.duration videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize preload:YES flags:0];
//    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
