//
//  NvEditStickerViewController.m
//  SDKDemo
//
//  Created by shizhouhu on 2018/6/26.
 //
//

#import "NvEditStickerViewController.h"
#import "NvUtils.h"
#import "NvLiveWindowPanelView.h"
#import "NvAlbumViewController.h"
#import "NvMoreStickerViewController.h"
#import "NvAssetCollectionViewCell.h"
#import "NvAssetCellModel.h"
#import "NvAssetManager.h"
#import "NvsCTimelineEditor.h"
#import "NvsVideoTrack.h"
#import "NvsVideoClip.h"
#import "NvTimelineData.h"
#import "NvTimelineUtils.h"
#import "NvTimelineStickerUtils.h"
#import "NvRectView.h"
#import "NvTimeLabelView.h"
#import "NvMoreFilterViewController.h"
#import "NvStickerModel.h"
#import "NvsTimelineAnimatedSticker.h"
#import "NvCustomStickerShapeViewController.h"
#import "NvSDKUtils.h"

#define NV_DEFAULT_STICKER_DURATION 5000000

@interface NvEditStickerViewController ()<UICollectionViewDelegate, UICollectionViewDataSource,NvsCTimelineEditorDelegate, NvRectViewDelegate, NvTimeLabelViewDelegate, NvsStreamingContextDelegate, NvLiveWindowPanelViewDelegate>

@property (nonatomic, strong) NvLiveWindowPanelView *liveWindowPanel;
@property (nonatomic, strong) NvsStreamingContext *streamingContext;

@property (nonatomic, strong) UIView *modifyPanelView;
@property (nonatomic, strong) UIView *selectPanelView;
@property (nonatomic, strong) UICollectionView *currentView;
@property (nonatomic, strong) UICollectionView *allCollectionView;
@property (nonatomic, strong) UICollectionView *customCollectionView;
@property (nonatomic, strong) NSMutableArray *allStickerArray;
@property (nonatomic, strong) NSMutableArray *customStickerArray;
@property (nonatomic, strong) NSMutableArray *currentStickerArray;
@property (nonatomic, strong) NvAssetManager *assetManager;
@property (nonatomic, strong) NvsCTimelineEditor *timelineEditor;
@property (nonatomic, strong) UIButton *allBtn;
@property (nonatomic, strong) UIButton *customBtn;
@property (nonatomic, strong) UIButton *finishButton;
@property (nonatomic, strong) UIView *allHintView;
@property (nonatomic, strong) UIView *customHintView;
@property (nonatomic, strong) NvRectView *boundingView;
@property (nonatomic, strong) NvTimeLabelView *timeLabel;
@property (nonatomic, strong) NvButton *playBtn;
@property (nonatomic, assign) int64_t inPoint;
@property (nonatomic, strong) NSIndexPath *currentIndexPath;

@property (nonatomic, assign) BOOL isAddState;//当前是否是添加操作

@property (nonatomic, strong) NSMutableArray <NvStickerModel *> *timeSpanArray;
@property (nonatomic, strong) NSMutableArray <NvStickerInfoModel *> *stickerInfoArray;
@property (nonatomic, strong) NvsTimelineAnimatedSticker *currentSticker;

@property (nonatomic, strong) NvStickerInfoModel *currentStickerInfoModel;
@property (nonatomic, strong) UIView *line;
@end

@implementation NvEditStickerViewController {
    NvTimelineData *timelineData;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.streamingContext = [NvsStreamingContext sharedInstance];
    self.allStickerArray = NSMutableArray.new;
    self.customStickerArray = NSMutableArray.new;
    self.view.backgroundColor = UIColorFromRGB(0x242728);
    
    [self initTimeline];
    [self addSubViews];
    
    self.assetManager = [NvAssetManager sharedInstance];
    [self.assetManager searchLocalAssets:ASSET_ANIMATED_STICKER];
    NSString *itemPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"sticker/normal"];
    [self.assetManager searchReservedAssets:ASSET_ANIMATED_STICKER bundlePath:itemPath];
    self.currentView = self.allCollectionView;
    self.currentStickerArray = self.allStickerArray;
    self.inPoint = 0;
    
    
}

- (void)addSubViews {
    self.liveWindowPanel = [[NvLiveWindowPanelView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.width)];
    _liveWindowPanel.editMode = self.editMode;
    _liveWindowPanel.delegate = self;
    _liveWindowPanel.forceHiddenControlPanel = YES;
    [self.view addSubview:_liveWindowPanel];
    [_liveWindowPanel connectTimeline:_timeline];
    [self seekTimeline:0];
    [_liveWindowPanel addTapScreenPause];
    
    self.modifyPanelView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREANHEIGHT - 214*SCREANSCALE, SCREANWIDTH, 214*SCREANSCALE)];
    [self.view addSubview:self.modifyPanelView];
    [self.modifyPanelView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.and.left.and.right.equalTo(self.view);
        make.height.equalTo(@(214*SCREANSCALE + INDICATOR));
    }];
    
    self.timeLabel = [[NvTimeLabelView alloc] initWithFrame:CGRectMake(0, 5*SCREANSCALE, SCREANWIDTH, 40*SCREANSCALE)];
    self.timeLabel.duration = self.timeline.duration;
    self.timeLabel.currentPos = 0;
    self.timeLabel.delegate = self;
    [self.modifyPanelView addSubview:self.timeLabel];
    [self.timeLabel updateLabel];
    
    self.timelineEditor = [[NvsCTimelineEditor alloc] initWithFrame:CGRectMake(0*SCREANSCALE, 40*SCREANSCALE, [UIScreen mainScreen].bounds.size.width, 49*SCREANSCALE)];
    self.timelineEditor.caneditTimeSpan = YES;
    self.timelineEditor.canOverlapTimeSpan = YES;
    
    NvsVideoTrack *videoTrack = [self.timeline getVideoTrackByIndex:0];
    NSMutableArray *clipPath = [NSMutableArray array];
    for (int i = 0; i < videoTrack.clipCount; i++) {
        NvsVideoClip *clip = [videoTrack getClipWithIndex:i];
        NvsCTimelineEditorInfo *info = [[NvsCTimelineEditorInfo alloc] init];
        info.mediaFilePath = clip.filePath;
        info.inPoint = clip.inPoint;
        info.outPoint = clip.outPoint;
        info.trimIn = clip.trimIn;
        info.trimOut = clip.trimOut;
        info.stillImageHint = false;
        [clipPath addObject:info];
    }
    
    [self.timelineEditor initTimelineEditor:clipPath timelineDuration:self.timeline.duration];
    self.timelineEditor.delegate = self;
    
    [self.modifyPanelView addSubview:self.timelineEditor];
    
    self.playBtn = [[NvButton alloc] initWithFrame:CGRectMake(0, 40*SCREANSCALE, 40*SCREANSCALE, 49*SCREANSCALE)];
    [self.playBtn setImage:[UIImage imageNamed:@"NvPlayback"] forState:UIControlStateNormal];
    [self.modifyPanelView addSubview:self.playBtn];
    [self.playBtn addTarget:self action:@selector(onPlayClicked) forControlEvents:UIControlEventTouchUpInside];
    self.playBtn.backgroundColor = UIColorFromRGB(0x242728);
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(SCREANWIDTH/2 - 20*SCREANSCALE, 110*SCREANSCALE, 40*SCREANSCALE, 40*SCREANSCALE)];
    [button setImage:[UIImage imageNamed:@"NvEditpreviewAdd"] forState:UIControlStateNormal];
    [self.modifyPanelView addSubview:button];
    
    [button addTarget:self action:@selector(onAddStickerClicked) forControlEvents:UIControlEventTouchUpInside];
    
    self.finishButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREANWIDTH/2 - 12*SCREANSCALE, 179*SCREANSCALE, 25*SCREANSCALE, 20*SCREANSCALE)];
    [self.finishButton setImage:[UIImage imageNamed:@"Nvcheck - material"] forState:UIControlStateNormal];
    [self.modifyPanelView addSubview:self.finishButton];
    
    [self.finishButton addTarget:self action:@selector(onFinishAddSticker) forControlEvents:UIControlEventTouchUpInside];
    
    self.selectPanelView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.selectPanelView];
    [self.selectPanelView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom).offset(-INDICATOR);
        make.height.equalTo(@(214*SCREANSCALE));
    }];
    self.selectPanelView.hidden = YES;
    
    [self initCategoryTabView];
    
    [self.view layoutIfNeeded];
    UIButton *button1 = [[UIButton alloc] initWithFrame:CGRectMake(SCREANWIDTH/2 - 12*SCREANSCALE, self.selectPanelView.height -35*SCREANSCALE - INDICATOR, 25*SCREANSCALE, 20*SCREANSCALE)];
    [button1 setImage:[UIImage imageNamed:@"Nvcheck - material"] forState:UIControlStateNormal];
    [self.selectPanelView addSubview:button1];
    
    [button1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.selectPanelView.mas_bottom).offset(-15*SCREANSCALE);
        make.centerX.equalTo(self.selectPanelView);
        make.width.equalTo(@(25*SCREANSCALE));
        make.height.equalTo(@(20*SCREANSCALE));
    }];
    
    [button1 addTarget:self action:@selector(onFinishSelectSticker) forControlEvents:UIControlEventTouchUpInside];
    
    self.line = [UIView new];
    self.line.backgroundColor = [UIColor nv_colorWithHexARGB:@"#1AFFFFFF"];
    [self.view addSubview:self.line];
    [self.line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.height.equalTo(@1);
        make.bottom.equalTo(button1.mas_top).offset(-12*SCREANSCALE);
    }];
    
    [self.view layoutIfNeeded];
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(85*SCREANSCALE, 85*SCREANSCALE);
    layout.minimumLineSpacing = 20*SCREANSCALE;
    layout.minimumInteritemSpacing = 32*SCREANSCALE;
    //    layout.sectionInset = UIEdgeInsetsMake(0, 16*SCREANSCALE, 0, 16*SCREANSCALE);
    self.allCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.allBtn.bottom+10, SCREEN_WDITH, 128*SCREANSCALE) collectionViewLayout:layout];
    self.allCollectionView.delegate = self;
    self.allCollectionView.dataSource = self;
    self.allCollectionView.backgroundColor = [UIColor clearColor];
    self.allCollectionView.showsHorizontalScrollIndicator = NO;
    [self.selectPanelView addSubview:self.allCollectionView];
    [self.allCollectionView registerClass:[NvAssetCollectionViewCell class] forCellWithReuseIdentifier:@"NvAssetCollectionViewCell"];
    
    [self initCustomCollectionView];
    
    [self initBoundingView];
    [self initTimespan];
}

- (void)initBoundingView {
    self.boundingView = [[NvRectView alloc] initWithFrame:CGRectZero type:NV_ANIMATED_STICKER];
    self.boundingView.layer.masksToBounds = YES;
    [self.liveWindowPanel.liveWindow addSubview:self.boundingView];
    [self.boundingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(@0);
    }];
    self.boundingView.delegate = self;
    self.boundingView.backgroundColor = [UIColor clearColor];
    self.boundingView.hidden = YES;
}

- (void)initTimeline {
    self.timeline = [NvTimelineUtils createTimeline:_editMode];
    [NvTimelineUtils recreateTimeline:self.timeline];
    
    timelineData = [NvTimelineData sharedInstance];
    self.timeSpanArray = [NSMutableArray array];
    NvTimelineData *data = [NvTimelineData sharedInstance];
    self.stickerInfoArray = [[NSMutableArray alloc] initWithArray:[data stickerDataArray] copyItems:YES];
    [NvTimelineUtils resetSticker:self.timeline stickerDataArray:self.stickerInfoArray];
    
    // 如果界面只需要显示贴纸，就把上面行注释掉，把下面两行打开
//    [NvTimelineUtils resetEditData:_timeline editDataArray:[[NvTimelineData sharedInstance] editDataArray]];
//    [NvTimelineUtils resetSticker:_timeline stickerDataArray:[[NvTimelineData sharedInstance] stickerDataArray]];
}

- (void)initTitleView {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREANWIDTH, 64*SCREANSCALE)];
    view.backgroundColor = [UIColor blackColor];
    [self.view addSubview:view];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(SCREANWIDTH/2 - 19*SCREANSCALE,
                                                               18*SCREANSCALE, SCREANWIDTH, 64*SCREANSCALE)];
    label.text = @"贴纸";
    label.textColor = [UIColor whiteColor];
    [view addSubview:label];
}
//[self addSticker:stickerInfo];

- (void)initCategoryTabView {
    UIView *sepLine = [[UIView alloc] initWithFrame:CGRectMake(0, 40*SCREANSCALE, SCREANWIDTH, 1)];
    sepLine.backgroundColor = [UIColor nv_colorWithHexARGB:@"#1AFFFFFF"];
    [self.selectPanelView addSubview:sepLine];
    
    UIView *tabview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREANWIDTH, 40*SCREANSCALE)];
    [self.selectPanelView addSubview:tabview];
    
    UIButton *downloadBtn = [[UIButton alloc] initWithFrame:CGRectMake(13*SCREANSCALE, 10*SCREANSCALE, 30*SCREANSCALE, 21*SCREANSCALE)];
    [downloadBtn setImage:[UIImage imageNamed:@"NvsFilterMore"] forState:UIControlStateNormal];
    [tabview addSubview:downloadBtn];
    
    self.allBtn = [[UIButton alloc] initWithFrame:CGRectMake(69*SCREANSCALE, 10*SCREANSCALE, 40*SCREANSCALE, 21*SCREANSCALE)];
    [self.allBtn setTitle:@"全部" forState:UIControlStateNormal];
    [self.allBtn setTitleColor:[UIColor nv_colorWithHexRGB:@"#909293"] forState:UIControlStateNormal];
    [self.allBtn setTitleColor:[UIColor nv_colorWithHexRGB:@"#4090e2"] forState:UIControlStateSelected];
    self.allBtn.selected = YES;
    self.allBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [tabview addSubview:self.allBtn];
    
    self.allHintView = [[UIView alloc] initWithFrame:CGRectMake(56*SCREANSCALE, 40*SCREANSCALE, 65*SCREANSCALE, 1)];
    self.allHintView.backgroundColor =  [UIColor nv_colorWithHexRGB:@"#4090e2"];
    [tabview addSubview:self.allHintView];
    
    self.customBtn = [[UIButton alloc] initWithFrame:CGRectMake(126*SCREANSCALE, 10*SCREANSCALE, 55*SCREANSCALE, 21*SCREANSCALE)];
    [self.customBtn setTitle:@"自定义" forState:UIControlStateNormal];
    [self.customBtn setTitleColor:[UIColor nv_colorWithHexRGB:@"#909293"] forState:UIControlStateNormal];
    [self.customBtn setTitleColor:[UIColor nv_colorWithHexRGB:@"#4090e2"] forState:UIControlStateSelected];
    self.customBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [tabview addSubview:self.customBtn];
    
    self.customHintView = [[UIView alloc] initWithFrame:CGRectMake(115*SCREANSCALE, 40*SCREANSCALE, 80*SCREANSCALE, 1)];
    self.customHintView.backgroundColor =  [UIColor nv_colorWithHexRGB:@"#4090e2"];
    [tabview addSubview:self.customHintView];
    self.customHintView.hidden = YES;
    
    [downloadBtn addTarget:self action:@selector(onDownloadClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.allBtn addTarget:self action:@selector(onAllClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.customBtn addTarget:self action:@selector(onCustomClicked) forControlEvents:UIControlEventTouchUpInside];
}

- (void)initCustomCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(85*SCREANSCALE, 85*SCREANSCALE);
    layout.minimumLineSpacing = 20*SCREANSCALE;
    layout.minimumInteritemSpacing = 32*SCREANSCALE;
//    layout.sectionInset = UIEdgeInsetsMake(0, 16*SCREANSCALE, 0, 0);
    self.customCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.allCollectionView.top, SCREEN_WDITH - 60 * SCREANSCALE, 128*SCREANSCALE) collectionViewLayout:layout];
    self.customCollectionView.delegate = self;
    self.customCollectionView.dataSource = self;
    self.customCollectionView.backgroundColor = [UIColor clearColor];
    self.customCollectionView.showsHorizontalScrollIndicator = NO;
    [self.selectPanelView addSubview:self.customCollectionView];
    [self.customCollectionView registerClass:[NvAssetCollectionViewCell class] forCellWithReuseIdentifier:@"NvAssetCollectionViewCell"];
    self.customCollectionView.hidden = YES;
}


- (void)initTimespan {
    NvsTimelineAnimatedSticker *nextSticker = [self.timeline getFirstAnimatedSticker];
    self.currentSticker = nextSticker;
    do {
        NvsCTimelineTimeSpan *timeSpan = [self.timelineEditor addTimeSpan:nextSticker.inPoint outPoint:nextSticker.outPoint];
        [self.timelineEditor selectTimeSpan:timeSpan];
        //存储一个infoModel对象用于使timelineEditor高亮
        NvStickerModel *infoModel = [NvStickerModel new];
        infoModel.currentSticker = nextSticker;
        infoModel.infoModel =  [self getStickerInfoModel:nextSticker];
        infoModel.timeSpan = timeSpan;
        if (nextSticker) {
            [self.timeSpanArray addObject:infoModel];
        }
        
        nextSticker = [self.timeline getNextAnimatedSticker:nextSticker];
    } while (nextSticker);
    
    self.currentSticker = [[self.timeline getAnimatedStickersByTimelinePosition:0] firstObject];
    if (self.currentSticker) {
        NvStickerModel *infoModel =  [self getCurrentTimeSpan:self.currentSticker];
        [self.timelineEditor selectTimeSpan:infoModel.timeSpan];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.boundingView.hidden = NO;
        });
    } else {
        self.boundingView.hidden = YES;
        [self.timelineEditor selectTimeSpan:nil];
    }
    [self seekTimeline:[_streamingContext getTimelineCurrentPosition:_timeline]];
    [self showBoundingView];
}

- (void)initReservedAsset:(NvAsset *)asset {
    if ([asset isReserved]) {
        if ([asset.uuid isEqualToString:@"0B2CA496-5DEB-4CAC-B01F-942B2C0B7580"]) {
            asset.categoryId = ANIMATED_STICKER_SILENT;
        }
        if ([asset.uuid isEqualToString:@"39A21E74-00C6-48F9-96B0-485114B6F8F5"]) {
            asset.categoryId = ANIMATED_STICKER_SILENT;
        }
        if ([asset.uuid isEqualToString:@"56A1D1CB-1CCA-40ED-B978-0ABA66021231"]) {
            asset.categoryId = ANIMATED_STICKER_SOUND;
        }
    }
}

- (void)onFinishSelectSticker {
    self.isAddState = NO;
    [self.liveWindowPanel addTapScreenPause];
    self.selectPanelView.hidden = YES;
    self.modifyPanelView.hidden = NO;
    [self clearSelectState];
    if (self.currentStickerInfoModel) {
//        [self.stickerInfoArray addObject:self.currentStickerInfoModel];
    }
    [self playbackTimeline:self.inPoint]; //重新从选择位置处开始播放
}

- (void)onDownloadClicked {
    NvMoreFilterViewController *vc = [[NvMoreFilterViewController alloc]init];
    vc.editModel = self.editMode;
    vc.type = ASSET_ANIMATED_STICKER;
    vc.isCapture = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)onAllClicked {
//    [_streamingContext stop];
    self.customCollectionView.hidden = YES;
    self.allCollectionView.hidden = NO;
    self.currentView = self.allCollectionView;
//    self.currentStickerArray = self.allStickerArray;
    [self updateAllStickers];
    [self.allCollectionView reloadData];
    self.allBtn.selected = YES;
    self.customBtn.selected = NO;
    self.allHintView.hidden = NO;
    self.customHintView.hidden = YES;
}

- (void)onCustomClicked {
//    [_streamingContext stop];
    self.allCollectionView.hidden = YES;
    self.customCollectionView.hidden = NO;
    self.currentView = self.customCollectionView;
//    self.currentStickerArray = self.customStickerArray;
    [self updateCustomStickers];
    [self.customCollectionView reloadData];
    self.allBtn.selected = NO;
    self.customBtn.selected = YES;
    self.allHintView.hidden = YES;
    self.customHintView.hidden = NO;
}

- (void)onAddStickerClicked {
    self.isAddState = YES;
    [self.liveWindowPanel removeTapScreenPause];
    self.modifyPanelView.hidden = YES;
    self.selectPanelView.hidden = NO;
    
    self.currentSticker = nil;
    self.boundingView.hidden = YES;
    
    [self.allCollectionView reloadData];
    [self.customCollectionView reloadData];
    
    self.inPoint = [_streamingContext getTimelineCurrentPosition:_timeline];
}

- (void)onFinishAddSticker {
    [NvTimelineUtils removeTimeline:self.timeline];
    NvTimelineData *data = [NvTimelineData sharedInstance];
    data.stickerDataArray = self.stickerInfoArray;
    
    NSMutableArray *order = [[NvTimelineData sharedInstance] dataOrder];
    [order removeObject:@"Sticker"];
    [order addObject:@"Sticker"];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)seekTimeline:(int64_t)postion {
    if (![_streamingContext seekTimeline:_timeline timestamp:postion videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:NvsStreamingEngineSeekFlag_ShowAnimatedStickerPoster])
        NSLog(@"定位时间线失败！");
}

- (void)onPlayClicked {
    int64_t curPos = [_streamingContext getTimelineCurrentPosition:self.timeline];
    if ([_streamingContext getStreamingEngineState] != NvsStreamingEngineState_Playback) {
        [_streamingContext playbackTimeline:self.timeline startTime:curPos endTime:-1 videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize
                                    preload:YES flags:0];
    } else {
        [_streamingContext stop];
    }
}

//获取字幕对应的infoModel对象
- (NvStickerInfoModel *)getStickerInfoModel:(NvsTimelineAnimatedSticker *) nextSticker {
    return (NvStickerInfoModel *)[nextSticker getAttachment:@"stickerInfoModel"];
}

- (UIView *)leftNavigationBarItemView {
    return [UIView new];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (self.currentView == self.allCollectionView) {
        [self updateAllStickers];
        [self.allCollectionView reloadData];
    } else {
        [self updateCustomStickers];
        [self.customCollectionView reloadData];
    }
    _streamingContext.delegate = self;
}

- (void)updateAllStickers {
    NSString *selectedUUID = nil;
    BOOL isPlay = NO;
    for (NvAssetCellModel *asset in self.allStickerArray) {
        if (asset.selected) {
            selectedUUID = asset.package;
            isPlay = asset.isPlay;
        }
    }
    
    [self.allStickerArray removeAllObjects];
    NSArray *array = [self.assetManager getUsableAssets:ASSET_ANIMATED_STICKER aspectRatio:AspectRatio_All categoryId:NV_CATEGORY_ID_ALL];
    for (NvAsset *asset in array) {
        [self initReservedAsset:asset];
        NvAssetCellModel *assetModel = NvAssetCellModel.new;
        assetModel.displayName = asset.name;
        assetModel.cover = [asset.coverUrl absoluteString];
        assetModel.size = [NvSDKUtils getAssetPackageSizeString:asset.remotePackageSize];
        assetModel.draw = [NvSDKUtils getAssetAspectRatioString:asset.aspectRatio];
        assetModel.package = asset.uuid;
        assetModel.categoryId = asset.categoryId;
        if ([assetModel.package isEqualToString:selectedUUID]) {
            assetModel.selected = YES;
            assetModel.isPlay = isPlay;
        }
        [self.allStickerArray addObject:assetModel];
    }
}

- (void)updateCustomStickers {
    NSMutableDictionary *customStickers = self.assetManager.customStickerDict;
    for (NSString *key in customStickers) {
        if ([self isCustomStickerExist:key])
            continue;
        NvCustomStickerInfo *info = customStickers[key];
        NvAssetCellModel *assetModel = NvAssetCellModel.new;
        assetModel.displayName = @"";
        assetModel.cover = info.imagePath;
        assetModel.package = info.uuid;
        assetModel.templateId = info.templateUuid;
        [self.customStickerArray insertObject:assetModel atIndex:self.customStickerArray.count];
    }
    [self addNoneSticker];
}

- (BOOL)isAssetExist:(NSString *)uuid {
    for (NvAssetCellModel *item in self.allStickerArray) {
        if ([item.package isEqualToString:uuid])
            return YES;
    }
    return NO;
}

- (BOOL)isCustomStickerExist:(NSString *)uuid {
    for (NvAssetCellModel *item in self.customStickerArray) {
        if ([item.package isEqualToString:uuid])
            return YES;
    }
    return NO;
}

- (void)addNoneSticker {
    for (NvAssetCellModel *item in _customStickerArray) {
        if ([item.cover isEqualToString:@"NvStickerAddButton"])
            return;
    }
    NvAssetCellModel *item = [NvAssetCellModel new];
    item.builtinName = nil;
    item.package = nil;
    item.selected = NO;
    item.cover = @"NvStickerAddButton";
    item.displayName = @"";
    [_customStickerArray insertObject:item atIndex:0];
}

- (void)clearSelectState {
    for (NvAssetCellModel *info in self.allStickerArray) {
        info.selected = NO;
    }
    for (NvAssetCellModel *info in self.customStickerArray) {
        info.selected = NO;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO];
}

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

- (void)removeSticker {
    [self.timelineEditor deleteTimeSpan:self.currentSticker.inPoint outPoint:self.currentSticker.outPoint];
    [self.timeline removeAnimatedSticker:self.currentSticker];
    [self.stickerInfoArray removeObject:(NvStickerInfoModel *)[self.currentSticker getAttachment:@"stickerInfoModel"]];
}

- (NvStickerModel *)getCurrentTimeSpan:(NvsTimelineAnimatedSticker *)currentSticker {
    NvStickerModel *infoModel;
    for (int i = 0; i < self.timeSpanArray.count; i++) {
        infoModel = self.timeSpanArray[i];
        if (infoModel.currentSticker == self.currentSticker) {
            return infoModel;
        }
    }
    return infoModel;
}

- (void)addSticker:(NvAssetCellModel *)stickerInfo {
    NvStickerInfoModel *info = NvStickerInfoModel.new;
    info.packageId = stickerInfo.templateId != nil ? stickerInfo.templateId : stickerInfo.package;
    info.isCustomSticer = stickerInfo.templateId != nil;
    info.customImagePath = stickerInfo.cover;
    info.inPoint = self.inPoint;
    info.outPoint = info.inPoint + NV_DEFAULT_STICKER_DURATION > _timeline.duration ? _timeline.duration : info.inPoint + NV_DEFAULT_STICKER_DURATION;
    info.isSlient = stickerInfo.categoryId == ANIMATED_STICKER_SILENT;
    self.currentStickerInfoModel = info;
    [self.stickerInfoArray addObject:info];
    
    if (info.isCustomSticer) {
        self.currentSticker = [self.timeline addCustomAnimatedSticker:info.inPoint duration:info.outPoint - info.inPoint animatedStickerPackageId:info.packageId customImagePath:info.customImagePath];
    } else {
        self.currentSticker = [self.timeline addAnimatedSticker:info.inPoint duration:info.outPoint - info.inPoint animatedStickerPackageId:info.packageId];
    }
    [self.currentSticker setAttachment:info forKey:@"stickerInfoModel"];
    
    NvsCTimelineTimeSpan *timeSpan = [self.timelineEditor addTimeSpan:info.inPoint outPoint:info.outPoint];
    
    NvStickerModel *infoModel = [NvStickerModel new];
    infoModel.currentSticker = self.currentSticker;
    infoModel.infoModel = info;
    infoModel.timeSpan = timeSpan;
    if (self.currentSticker) {
        [self.timeSpanArray addObject:infoModel];
    }
    
    float currentVolume;
    [self.currentSticker getVolumeGain:&currentVolume rightVolumeGain:&currentVolume];
    [self.boundingView setVolume:currentVolume > 0];
}

- (void)showBoundingView {
    if (self.currentSticker == nil) {
        self.boundingView.hidden = YES;
        return;
    }
    
    BOOL flip = [self.currentSticker getHorizontalFlip];
    if (flip)
        [self.currentSticker setHorizontalFlip:!flip];
    [self.boundingView setPoints:[NvTimelineStickerUtils getStickerBoundingPoints:_timeline liveWindow:_liveWindowPanel.liveWindow stickerInfo:[self getStickerInfoModel:self.currentSticker]]];
    [self.currentSticker setHorizontalFlip:flip];
    self.boundingView.hidden = NO;
    
    NvStickerInfoModel *modelInfo = [self getStickerInfoModel:self.currentSticker];
    [self.boundingView hideVoiceButton:modelInfo == nil ? YES : modelInfo.isSlient];
    [self.boundingView setVolume:modelInfo.volume > 0];
}

- (void)playbackTimeline:(int64_t)pos {
    [self.streamingContext playbackTimeline:self.timeline startTime:pos endTime:-1 videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize preload:YES flags:0];
}

- (UIImage *)getImage:(PHAsset *)asset {
    __block UIImage *resultImage;
    PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];
    requestOptions.resizeMode   = PHImageRequestOptionsResizeModeExact;
    requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    
    // this one is key
    requestOptions.synchronous = YES;
    [[PHImageManager defaultManager] requestImageForAsset:asset
                                               targetSize:PHImageManagerMaximumSize
                                              contentMode:PHImageContentModeAspectFit
                                                  options:requestOptions
                                            resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                                                resultImage = result;
                                            }
     ];
    return resultImage;
}

# pragma mark 代理UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView == self.allCollectionView) {
        return self.allStickerArray.count;
    } else {
        return self.customStickerArray.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.allCollectionView) {
        NvAssetCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NvAssetCollectionViewCell" forIndexPath:indexPath];
        [cell renderCellWithItem:_allStickerArray[indexPath.row]];
        return cell;
    } else {
        NvAssetCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NvAssetCollectionViewCell" forIndexPath:indexPath];
        [cell renderCellWithItem:_customStickerArray[indexPath.row]];
        return cell;
    }
}

# pragma mark 代理UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0 && collectionView == self.customCollectionView) {

        [_streamingContext stop];
        self.currentStickerArray = self.customStickerArray;
        self.currentIndexPath = indexPath;
        
        NvAlbumViewController *vc = [NvAlbumViewController new];
        vc.isOnlyImage = YES;
        vc.mutableSelect = NO;
        vc.delegate = self;
        [vc customSelectAssetButtonText:@"开始制作贴纸"];
        [self.navigationController pushViewController:vc animated:YES];

        return;
    }
    if (collectionView == self.customCollectionView) {
        self.currentStickerArray = self.customStickerArray;
    } else {
        self.currentStickerArray = self.allStickerArray;
    }
    
    if (self.currentIndexPath != nil && [self.currentIndexPath isEqual:indexPath]) {
        NvAssetCellModel *stickerInfo = self.currentStickerArray[indexPath.row];
        if ([NvSDKUtils getSDKContext].getStreamingEngineState != NvsStreamingEngineState_Playback) {
            stickerInfo.isPlay = YES;
                if (![[NvSDKUtils getSDKContext] playbackTimeline:self.timeline startTime:self.liveWindowPanel.currentTime endTime:self.timeline.duration videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize preload:YES flags:0]) {
                    NSLog(@"播放时间线失败！");
                    return;
                }
        } else {
            stickerInfo.isPlay = NO;
            [[NvSDKUtils getSDKContext] stop];
        }
        [self.currentView reloadData];
    }else{
        // 清除所有选中状态
        [self clearSelectState];
        
        // 先删除之前添加的sticker
        [self removeSticker];
        
        [self seekTimeline:self.inPoint];
        
        // 添加sticker
        NvAssetCellModel *stickerInfo = self.currentStickerArray[indexPath.row];
        stickerInfo.selected = YES;
        stickerInfo.isPlay = YES;
        [self addSticker:stickerInfo];
        
        [self showBoundingView];
        [self playbackTimeline:[_streamingContext getTimelineCurrentPosition:self.timeline]];
        self.currentIndexPath = indexPath;
        [self.currentView reloadData];
    }
}

- (void)nvAlbumViewController:(NvAlbumViewController *)albumViewController selectAlbumAssets:(NSMutableArray <NvAlbumAsset *>*)assets {
    NvCustomStickerShapeViewController *vc = NvCustomStickerShapeViewController.new;
//    vc.editMode = weakSelf.editMode;
    vc.selectedImage = [self getImage:assets.firstObject.asset];
    [self.navigationController pushViewController:vc animated:YES];
}

# pragma mark 代理NvRectViewDelegate
- (void)rectView:(NvRectView*)rectView close:(UIButton*)close {
    self.currentStickerInfoModel = nil;
    NvStickerModel *modelInfo = [self getCurrentTimeSpan:self.currentSticker];
    [self.timelineEditor selectTimeSpan:modelInfo.timeSpan];
    [self.timelineEditor deleteSelectedTimeSpan];
    
    [self.timeline removeAnimatedSticker:self.currentSticker];
    [self.stickerInfoArray removeObject:modelInfo.infoModel];
    [self.timeSpanArray removeObject:modelInfo];
    
    self.currentSticker = [[self.timeline getAnimatedStickersByTimelinePosition:[self.streamingContext getTimelineCurrentPosition:self.timeline]] lastObject];
    
    NvStickerModel *modelInfonext = [self getCurrentTimeSpan:self.currentSticker];
    [self.timelineEditor selectTimeSpan:modelInfonext.timeSpan];
    if (self.currentSticker) {
        [self showBoundingView];
    } else {//删完了，就直接隐藏
        self.boundingView.hidden = YES;
    }
    
    [self seekTimeline:[_streamingContext getTimelineCurrentPosition:_timeline]];
    
    if (!self.selectPanelView.hidden) {
        [self clearSelectState];
        [self.allCollectionView reloadData];
        [self.customCollectionView reloadData];
    }
}

- (void)rectView:(NvRectView *)rectView toggleVolume:(UIButton *)toggleVolume {
    float currentVolume;
    [self.currentSticker getVolumeGain:&currentVolume rightVolumeGain:&currentVolume];
    [self.currentSticker setVolumeGain:1-currentVolume rightVolumeGain:1-currentVolume];
    NvStickerInfoModel *modelInfo = [self getStickerInfoModel:self.currentSticker];
    modelInfo.volume = 1 - currentVolume;
    
    [self.boundingView setVolume:modelInfo.volume > 0];
}

- (void)rectView:(NvRectView *)rectView horizontalFlip:(UIButton *)horizontalFlip {
    BOOL isFlip = [self.currentSticker getHorizontalFlip];
    isFlip = !isFlip;
    [self.currentSticker setHorizontalFlip:isFlip];
    [self seekTimeline:[_streamingContext getTimelineCurrentPosition:_timeline]];
}

- (CGPoint)getCenterWithArray:(NSArray*)array {
    NSValue *leftTopValue = array[0];
    NSValue *rightBottomValue = array[2];
    CGPoint topLeftCorner = [leftTopValue CGPointValue];
    CGPoint rightBottomCorner = [rightBottomValue CGPointValue];
    return CGPointMake((topLeftCorner.x+rightBottomCorner.x)/2, (topLeftCorner.y+rightBottomCorner.y)/2);
}

- (void)rectView:(NvRectView*)rectView rotate:(float)rotate scale:(float)scale {
    
    NSArray *array = [self.currentSticker getBoundingRectangleVertices];
    CGPoint center = [self getCenterWithArray:array];
    
    [self.currentSticker scaleAnimatedSticker:scale anchor:center];
    [self.currentSticker rotateAnimatedSticker:rotate anchor:center];
    [self seekTimeline:[_streamingContext getTimelineCurrentPosition:_timeline]];
    [self showBoundingView];
    
    NvStickerModel *modelInfo = [self getCurrentTimeSpan:self.currentSticker];
    modelInfo.infoModel.rotation = [self.currentSticker getRotationZ];
    modelInfo.infoModel.scale = [self.currentSticker getScale];
}

- (void)rectView:(NvRectView*)rectView currentPoint:(CGPoint)currentPoint previousPoint:(CGPoint)previousPoint {
    
    CGPoint p1 = [self.liveWindowPanel.liveWindow mapViewToCanonical:currentPoint];
    CGPoint p2 = [self.liveWindowPanel.liveWindow mapViewToCanonical:previousPoint];
    CGPoint newPoint = CGPointMake(p1.x-p2.x, p1.y-p2.y);
    [self.currentSticker translateAnimatedSticker:newPoint];
    [self seekTimeline:[_streamingContext getTimelineCurrentPosition:_timeline]];
    [self showBoundingView];
    
    NvStickerModel *modelInfo = [self getCurrentTimeSpan:self.currentSticker];
    modelInfo.infoModel.translation = [self.currentSticker getTransltion];
    
}

- (void)rectView:(NvRectView *)rectView touchBeganPoint:(CGPoint)point {
    if (!self.isAddState) {
        NvStickerInfoModel *info = [NvTimelineStickerUtils getStickerByPoint:_timeline liveWindow:_liveWindowPanel.liveWindow point:point];
        if (info == nil) {
            return;
        }
        self.currentSticker = [NvTimelineStickerUtils findStickerObject:_timeline stickerInfo:info];
        
        for (int i = 0; i < self.timeSpanArray.count; i++) {
            NvStickerModel *model = self.timeSpanArray[i];
            if ([model.infoModel.uuid isEqualToString:info.uuid]) {
                [self.timelineEditor selectTimeSpan:model.timeSpan];
                break;
            }
        }
        [self showBoundingView];
    }
}

- (void)rectView:(NvRectView *)rectView isHidden:(BOOL)isHidden {
    NSLog(@"我改变了吗%d",self.isAddState);
    if (!self.isAddState) {
        if (isHidden) {
            [self.liveWindowPanel addTapScreenPause];
        } else {
            [self.liveWindowPanel removeTapScreenPause];
        }
    }
}

- (void)rectView:(NvRectView *)rectView touchUpInside:(CGPoint)point {
    if (self.currentSticker) {
        NSArray *array = [self.currentSticker getBoundingRectangleVertices];
        NSValue *leftTopValue = array[0];
        NSValue *leftBottomValue = array[1];
        NSValue *rightBottomValue = array[2];
        NSValue *rightTopValue = array[3];
        CGPoint topLeftCorner = [leftTopValue CGPointValue];
        CGPoint bottomLeftCorner = [leftBottomValue CGPointValue];
        CGPoint rightBottomCorner = [rightBottomValue CGPointValue];
        CGPoint rightTopCorner = [rightTopValue CGPointValue];
        
        topLeftCorner = [self.liveWindowPanel.liveWindow mapCanonicalToView:topLeftCorner];
        rightBottomCorner = [self.liveWindowPanel.liveWindow mapCanonicalToView:rightBottomCorner];
        bottomLeftCorner = [self.liveWindowPanel.liveWindow mapCanonicalToView:bottomLeftCorner];
        rightTopCorner = [self.liveWindowPanel.liveWindow mapCanonicalToView:rightTopCorner];
        
        CGMutablePathRef pathRef=CGPathCreateMutable();
        CGPathMoveToPoint(pathRef, NULL, topLeftCorner.x, topLeftCorner.y);
        CGPathAddLineToPoint(pathRef, NULL, bottomLeftCorner.x, bottomLeftCorner.y);
        CGPathAddLineToPoint(pathRef, NULL, rightBottomCorner.x, rightBottomCorner.y);
        CGPathAddLineToPoint(pathRef, NULL, rightTopCorner.x, rightTopCorner.y);
        CGPathCloseSubpath(pathRef);
        bool isIn = CGPathContainsPoint(pathRef, nil, point, false);
        CGPathRelease(pathRef);
        if(isIn){
            [self.boundingView setPoints:@[[NSValue valueWithCGPoint:[self.liveWindowPanel.liveWindow convertPoint:topLeftCorner toView:self.boundingView]],[NSValue valueWithCGPoint:[self.liveWindowPanel.liveWindow convertPoint:bottomLeftCorner toView:self.boundingView]],[NSValue valueWithCGPoint:[self.liveWindowPanel.liveWindow convertPoint:rightBottomCorner toView:self.boundingView]],[NSValue valueWithCGPoint:[self.liveWindowPanel.liveWindow convertPoint:rightTopCorner toView:self.boundingView]]]];
            NSLog(@"在内部");
            
        } else {
            //                NSLog(@"touchUpInside播放");
            if ([NvSDKUtils getSDKContext].getStreamingEngineState != NvsStreamingEngineState_Playback) {
                if (!self.isAddState) {
                    if (![[NvSDKUtils getSDKContext] playbackTimeline:self.timeline startTime:self.liveWindowPanel.currentTime endTime:self.timeline.duration videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize preload:YES flags:0]) {
                        NSLog(@"播放时间线失败！");
                        return;
                    }
                }
            } else {
                [[NvSDKUtils getSDKContext] stop];
            }
        }
    }
}

# pragma mark 代理NvsCTimelineEditorDelegate
- (void)timelineEditor:(id)timelineEditor dragHandleStarted:(int64_t)timestamp isInPoint:(bool)isInPoint {
    
}

- (void)timelineEditor:(id)timelineEditor draggingHandle:(int64_t)timestamp isInPoint:(bool)isInPoint {
    NvStickerModel *model = [self getCurrentTimeSpan:self.currentSticker];
    if (isInPoint) {
        model.infoModel.inPoint = timestamp;
        [self seekTimeline:timestamp];
        self.timeLabel->timeLabel.text= [NSString stringWithFormat:@"%@/%@",[NvUtils convertTimecodePrecision:timestamp],[NvUtils convertTimecodePrecision:self.timeline.duration]];
    } else {
        model.infoModel.outPoint = timestamp;
        [self seekTimeline:timestamp-10000];
        self.timeLabel->timeLabel.text= [NSString stringWithFormat:@"%@/%@",[NvUtils convertTimecodePrecision:timestamp-10000],[NvUtils convertTimecodePrecision:self.timeline.duration]];
    }
}

- (void)timelineEditor:(id)timelineEditor dragHandleEnded:(int64_t)timestamp isInPoint:(bool)isInPoint {

    [self.timelineEditor setTimelinePosition:timestamp];
    NvStickerModel *modelnext = [self getCurrentTimeSpan:self.currentSticker];
    if (self.currentSticker) {
        [self.timelineEditor selectTimeSpan:modelnext.timeSpan];
    }
    
    if (isInPoint) {
        [self.currentSticker changeInPoint:timestamp];
        [self seekTimeline:timestamp];
    } else {
        [self.currentSticker changeOutPoint:timestamp];
        [self seekTimeline:timestamp-10000];
    }
}

- (void)timelineEditor:(id)timelineEditor dragScrollingTimeline:(int64_t)timestamp {
    [self seekTimeline:timestamp];
    self.liveWindowPanel.currentTime = timestamp;
    self.timeLabel.currentPos = timestamp;
    [self.timeLabel updateLabel];
}

- (void)timelineEditor:(id)timelineEditor dragScrollTimelineEnded:(int64_t)timestamp {
    
    NvStickerModel *model = [self getCurrentTimeSpan:self.currentSticker];
    [self.timelineEditor selectTimeSpan:model.timeSpan];
    
    self.currentSticker = [[self.timeline getAnimatedStickersByTimelinePosition:[self.streamingContext getTimelineCurrentPosition:self.timeline]] lastObject];
    self.boundingView.hidden = self.currentSticker?NO:YES;
    
    if (self.currentSticker) {
        NvStickerModel *modelInfo = [self getCurrentTimeSpan:self.currentSticker];
        [self.timelineEditor selectTimeSpan:modelInfo.timeSpan];
    } else {
        [self.timelineEditor selectTimeSpan:nil];
    }
    [self seekTimeline:timestamp];
    
    [self showBoundingView];
}

# pragma mark 代理NvTimeLabelViewDelegate
- (void)onZoomInClicked {
    [_timelineEditor zoomIn];
}

- (void)onZoomOutClicked {
    [_timelineEditor zoomOut];
}

# pragma mark 代理NvLiveWindowPanelViewDelegate
- (void)didPlaybackTimelinePosition:(NvsTimeline *)timeline position:(int64_t)position {
    _liveWindowPanel.currentTime = position;
    if (self.selectPanelView.hidden) { //在调节页面
        [_timelineEditor clearTimeSpanSelection]; //清除选中状态
        self.timeLabel.currentPos = position;
        [self.timeLabel updateLabel];
        
        [self.timelineEditor setTimelinePosition:position];
        
    } else { //在添加页面
        
        if (position >= self.currentSticker.outPoint) {
            [self seekTimeline:self.currentSticker.inPoint];
            [self.timelineEditor setTimelinePosition:self.currentSticker.inPoint];
            [self.timelineEditor selectTimeSpan:self.currentSticker.inPoint outPoint:self.currentSticker.outPoint];
            _liveWindowPanel.currentTime = self.currentSticker.inPoint;
        }
    }
}

- (void)didPlaybackStopped:(NvsTimeline *)timeline {
//    _liveWindowPanel.currentTime = position;
    if (self.selectPanelView.hidden) { //在调节页面
        
        self.currentSticker = [[self.timeline getAnimatedStickersByTimelinePosition:[self.streamingContext getTimelineCurrentPosition:self.timeline]] lastObject];
        self.boundingView.hidden = self.currentSticker?NO:YES;
        
        [self.timelineEditor clearTimeSpanSelection];
        [self.timelineEditor selectTimeSpan:self.currentSticker.inPoint outPoint:self.currentSticker.outPoint];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self seekTimeline:[self->_streamingContext getTimelineCurrentPosition:self->_timeline]];
            [self showBoundingView];
        });

        
    } else {
        [self seekTimeline:self.currentSticker.inPoint];
        [self showBoundingView];
    }
}

- (void)didPlaybackEOF:(NvsTimeline *)timeline {
    _liveWindowPanel.currentTime = 0;
    if (self.selectPanelView.hidden) { //在调节页面
        self.timeLabel.currentPos = 0;
        [self.timeLabel updateLabel];
        
        [self.timelineEditor setTimelinePosition:self.timeLabel.currentPos];
        [self seekTimeline:0];
        
        self.currentSticker = [[self.timeline getAnimatedStickersByTimelinePosition:[self.streamingContext getTimelineCurrentPosition:self.timeline]] lastObject];
        [self.timelineEditor clearTimeSpanSelection];
        [self.timelineEditor selectTimeSpan:self.currentSticker.inPoint outPoint:self.currentSticker.outPoint];
        [self showBoundingView];
    } else {
        
    }
}

- (void)sliderValueChanged:(float)value {
    self.timeLabel.currentPos = value*self.timeline.duration;
    [self.timeLabel updateLabel];
    
    [self.timelineEditor setTimelinePosition:self.timeLabel.currentPos];
}

- (void)didStreamingEngineStateChanged:(NvsStreamingEngineState)state {
    if (self.selectPanelView.hidden) { //在调节页面
        if (state != NvsStreamingEngineState_Playback) {
            [self.playBtn setImage:[UIImage imageNamed:@"NvPlayback"] forState:UIControlStateNormal];
        } else {
            [self.playBtn setImage:[UIImage imageNamed:@"NvPause"] forState:UIControlStateNormal];
            self.boundingView.hidden = YES;
            [self.timelineEditor clearTimeSpanSelection];
        }
    } else {    //在添加页面

        NvAssetCellModel *stickerInfo = self.currentStickerArray[self.currentIndexPath.row];
        if (state != NvsStreamingEngineState_Playback) {
            [self.playBtn setImage:[UIImage imageNamed:@"NvPlayback"] forState:UIControlStateNormal];
            stickerInfo.isPlay = NO;
            
        } else {
            [self.playBtn setImage:[UIImage imageNamed:@"NvPause"] forState:UIControlStateNormal];
            self.boundingView.hidden = YES;
            stickerInfo.isPlay = YES;
        }
        [self.currentView reloadData];
    }

}
@end
