//
//  NvTransitionViewController.m
//  SDKDemo
//
//  Created by 刘东旭 on 2018/6/29.
 //
//

#import "NvTransitionViewController.h"
#import "NvTransitionCollectionViewCell.h"
#import "NvClipCollectionViewCell.h"
#import "NvClipItem.h"
#import "NvTransitionItem.h"
#import "NvMoreDownloadViewController.h"
#import "NvTimelineData.h"
#import "NvTimelineImageUtils.h"
#import "NvTimelineUtils.h"
#import "NvMoreFilterViewController.h"
#import "NvAlbumViewController.h"
#import "NvsStreamingContext.h"
#import "NvSDKUtils.h"
#import "NvAssetManager.h"

@interface NvTransitionViewController ()<UICollectionViewDelegate, UICollectionViewDataSource,NvAssetManagerDelegate> {
    int64_t outpoint;
    int64_t inPoint;
}

@property (nonatomic, strong) UICollectionView *clipCollectionView;
@property (nonatomic, strong) UICollectionView *transitionCollectionView;
@property (nonatomic, strong) NSMutableArray<NvClipItem *> *clipDataSource;
@property (nonatomic, strong) NSMutableArray<NvTransitionItem *> *transitionDataSource;

@property (nonatomic, strong) UIButton *moreButton;
@property (nonatomic, strong) UILabel *moreLabel;

@property (nonatomic, strong) UIButton *okButton;

@property (nonatomic, strong) NvAssetManager *assetManager;
@property (nonatomic, strong) NSIndexPath *selectIndexPath;

@property (nonatomic, assign) BOOL isSelected;

@property (nonatomic, strong) UIView *line;

@end

@implementation NvTransitionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.transitionDataSource = [NSMutableArray array];
    // Do any additional setup after loading the view.
    self.title = @"转场";
    [self.liveWindowPanel hiddenVolumeButton];
    // 初始化列表数据
    [self initDataFormTimeline];
    /// MARK: UI布局
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.itemSize = CGSizeMake(110*SCREANSCALE, 48*SCREANSCALE);
    flowLayout.minimumInteritemSpacing = 5*SCREANSCALE;
    self.clipCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    self.clipCollectionView.showsHorizontalScrollIndicator = NO;
    self.clipCollectionView.delegate = self;
    self.clipCollectionView.dataSource = self;
    self.clipCollectionView.backgroundColor = [UIColor nv_colorWithHexRGB:@"#242728"];
    [self.view addSubview:self.clipCollectionView];
    [self.clipCollectionView registerClass:[NvClipCollectionViewCell class] forCellWithReuseIdentifier:@"NvClipCollectionViewCell"];
    
    [self.clipCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(8*SCREANSCALE);
        make.top.equalTo(@(SCREEN_WDITH+13*SCREANSCALEHEIGHT));
        make.right.equalTo(@(-8*SCREANSCALE));
        make.height.equalTo(@(56*SCREANSCALEHEIGHT));
    }];
    
    self.moreButton = [UIButton nv_buttonWithTitle:@"" textColor:nil fontSize:-1 image:[NvUtils imageWithName:@"NvsFilterMore"]];
    [self.view addSubview:self.moreButton];
    __weak typeof(self)weakSelf = self;
    [self.moreButton nv_BtnClickHandler:^{
        NvMoreFilterViewController *vc = [[NvMoreFilterViewController alloc]init];
        vc.editModel = weakSelf.editMode;
        vc.type = ASSET_VIDEO_TRANSITION;
        vc.isCapture = NO;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    self.moreLabel = [UILabel nv_labelWithText:@"更多" fontSize:12 textColor:[UIColor nv_colorWithHexARGB:@"#CCFFFFFF"]];
    [self.view addSubview:self.moreLabel];
    
    UICollectionViewFlowLayout *transitionFlowLayout = [[UICollectionViewFlowLayout alloc] init];
    transitionFlowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    transitionFlowLayout.itemSize = CGSizeMake(77*SCREANSCALE, 49*SCREANSCALE);
    transitionFlowLayout.minimumInteritemSpacing = 8*SCREANSCALE;
    self.transitionCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:transitionFlowLayout];
    self.transitionCollectionView.showsHorizontalScrollIndicator = NO;
    self.transitionCollectionView.delegate = self;
    self.transitionCollectionView.dataSource = self;
    self.transitionCollectionView.backgroundColor = [UIColor nv_colorWithHexRGB:@"#242728"];
    [self.view addSubview:self.transitionCollectionView];
    [self.transitionCollectionView registerClass:[NvTransitionCollectionViewCell class] forCellWithReuseIdentifier:@"NvTransitionCollectionViewCell"];
    
    [self.moreButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(8*SCREANSCALE));
        make.top.equalTo(self.clipCollectionView.mas_bottom).offset(8*SCREANSCALEHEIGHT);
        make.width.equalTo(@(57*SCREANSCALE));
        make.height.equalTo(@(49*SCREANSCALE));
    }];
    [self.moreLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.moreButton.mas_bottom).offset(8*SCREANSCALE);
        make.centerX.equalTo(self.moreButton);
    }];
    [self.transitionCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.moreButton.mas_right).offset(8*SCREANSCALE);
        make.top.equalTo(self.clipCollectionView.mas_bottom).offset(8*SCREANSCALE);
        make.right.equalTo(@(-8*SCREANSCALE));
        make.bottom.equalTo(self.moreLabel.mas_bottom);
    }];
    
    self.okButton = [UIButton nv_buttonWithTitle:nil textColor:nil fontSize:-1 image:[NvUtils imageWithName:@"Nvcheck - material"]];
    [self.view addSubview:self.okButton];
    
    [self.okButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.width.equalTo(@(25*SCREANSCALEHEIGHT));
        make.height.equalTo(@(20*SCREANSCALEHEIGHT));
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-15*SCREANSCALEHEIGHT);
        } else {
            make.bottom.equalTo(@(-15*SCREANSCALEHEIGHT));
        }
    }];
    
    [self.okButton nv_BtnClickHandler:^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
    
    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(self.okButton.mas_top).offset(-12*SCREANSCALE);
    }];
    
    self.assetManager = [NvAssetManager sharedInstance];
    [self.assetManager searchLocalAssets:ASSET_VIDEO_TRANSITION];
    [self getStyleDefaultData];
    [self.transitionCollectionView reloadData];
    
    self.selectIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
}

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

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getStyleDefaultData];
    [self.transitionCollectionView reloadData];
}

//初始化timeline
- (void)initDataFormTimeline {
    self.clipDataSource = [NSMutableArray array];
    for (int i = 0; i < [[NvTimelineData sharedInstance] editDataArray].count; i++) {
        NvEditDataModel *clipInfo = [[NvTimelineData sharedInstance] editDataArray][i];
        NvClipItem *item = [NvClipItem new];
        item.isImage = clipInfo.isImage;
        item.isPhotoAlbum = clipInfo.isPhotoAlbum;
        item.isLoading = clipInfo.isLoading;
        item.videoPath = clipInfo.videoPath;
        item.image = clipInfo.thumImage;
        item.localIdentifier = clipInfo.localIdentifier;
        item.trimIn = clipInfo.trimIn;
        if (i == [[NvTimelineData sharedInstance] editDataArray].count - 1) {
            item.isLast = YES;
            item.transitionImageUrl = nil;
        } else {
            NvTransitionInfoModel *transitionInfoModel = [[NvTimelineData sharedInstance] transitionDataArray][0];
            
            item.isLast = NO;
            if (transitionInfoModel.builtinName != 0) {
                item.transitionImageUrl = [NvSDKUtils getTransitionsCoverName:transitionInfoModel.builtinName];
            }else{
                item.transitionImageUrl = transitionInfoModel.imageUrl;
            }
        }
        [self.clipDataSource addObject:item];
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.clipCollectionView reloadData];
    });
    [self getStyleDefaultData];
    [self.clipCollectionView reloadData];
}
//获取专场默认数据
- (void)getStyleDefaultData {
    if (_transitionDataSource) {
        [_transitionDataSource removeAllObjects];
    }
    NvTransitionInfoModel *transitionInfoModel = [[NvTimelineData sharedInstance] transitionDataArray].firstObject;
    NSLog(@"===%@",transitionInfoModel.builtinName);
    NSLog(@"====%@",transitionInfoModel.imageUrl);
    NSLog(@"====%@",transitionInfoModel.uuid);
    NSLog(@"====%@",transitionInfoModel.packageId);
    self.assetManager = [NvAssetManager sharedInstance];
    self.assetManager.delegate = self;
    [self.assetManager searchLocalAssets:ASSET_VIDEO_TRANSITION];
    
    AspectRatio ratio;
    switch (self.editMode) {
        case NvEditMode16v9:
            ratio = AspectRatio_16v9;
            break;
        case NvEditMode1v1:
            ratio = AspectRatio_1v1;
            break;
        case NvEditMode9v16:
            ratio = AspectRatio_9v16;
            break;
        case NvEditMode3v4:
            ratio = AspectRatio_3v4;
            break;
        case NvEditMode4v3:
            ratio = AspectRatio_4v3;
            break;
        default:
            ratio = AspectRatio_All;
            break;
    }
    
    NSArray *array = [self.assetManager getUsableAssets:ASSET_VIDEO_TRANSITION aspectRatio:ratio categoryId:NV_CATEGORY_ID_ALL];
//    BOOL isNone = NO;
    for (NvAsset *asset in array) {
        NvTransitionItem *item = [NvTransitionItem new];
        item.imageUrl = [asset.coverUrl absoluteString];
        item.name = asset.name;
        item.packageId = asset.uuid;
        item.builtinName = nil;
        if (transitionInfoModel.builtinName.length == 0) {
            if ([transitionInfoModel.packageId isEqualToString:asset.uuid]) {
                item.isSelect = YES;
            }
        }
        [self.transitionDataSource addObject:item];
//        if (asset.name && [asset.name isEqualToString:@"无"]) {
//            isNone = YES;
//        }
    }
    NSArray *videoFxArray = @[@"Fade", @"Turning", @"Swap", @"Stretch In", @"Page Curl", @"Lens Flare", @"Star", @"Dip To Black", @"Dip To White", @"Push To Right",@"Push To Top",@"Upper Left Into"];
    NSArray *videoFxDisplayArray =@[@"Fade", @"Turning", @"Swap", @"Stretch In", @"Page Curl", @"Lens Flare", @"Star", @"Dip To Black", @"Dip To White", @"Push To Right",@"Push To Top",@"Upper Left Into"];
    for (int i = 0; i < videoFxArray.count; i++) {
        NvTransitionItem *item = [NvTransitionItem new];
        item.packageId = videoFxArray[i];
        item.imageUrl = [NvSDKUtils getTransitionsCoverName:videoFxArray[i]];
        item.name = videoFxDisplayArray[i];
        item.builtinName = videoFxArray[i];
        if (transitionInfoModel.builtinName.length != 0) {
            if ([transitionInfoModel.builtinName isEqualToString:item.name]) {
                item.isSelect = YES;
            }
        }
        [self.transitionDataSource addObject:item];
    }
    NvTransitionItem *item = [NvTransitionItem new];
    item.imageUrl = @"NvsFilterNone";
    item.name = @"无";
    item.packageId = nil;
//    if (isNone) {
//        item.isSelect = YES;
//    } else {
//        item.isSelect = NO;
//    }
    
    [self.transitionDataSource insertObject:item atIndex:0];
}

//设置专场
- (void)setTransitionWithId:(NvTransitionItem *)transitionItem{
    if (!_isSelected) {
        NvClipItem *item = self.clipDataSource[0];
        item.isSelect = YES;
        [self.clipCollectionView reloadData];
        NSArray *array = [[NvTimelineData sharedInstance] editDataArray];
        outpoint = [NvTimelineUtils getClipOutpoint:self.timeline clipInfo:[array firstObject]];
        outpoint = outpoint - 0.5*NV_TIME_BASE;
    }
//    //最后一段不需要设置转场
//    if (self.selectIndexPath.row >= [[NvTimelineData sharedInstance] transitionDataArray].count) {
//        [self.clipCollectionView reloadData];
//        [self seekTimeline];
//        return;
//    }
    
//    [[NvTimelineData sharedInstance] transitionDataArray][self.selectIndexPath.row].packageId = packageId;
    for (NvTransitionInfoModel *info in [[NvTimelineData sharedInstance] transitionDataArray]) {
        info.packageId = transitionItem.packageId;
        info.builtinName = transitionItem.builtinName;
        info.imageUrl = transitionItem.imageUrl;
    }
//    [[NvTimelineData sharedInstance] transitionDataArray][self.selectIndexPath.row].imageUrl = [self getTransitionImageUrl:packageId];
//    for (NvTransitionItem *item in self.transitionDataSource) {
        [[NvTimelineData sharedInstance] transitionDataArray][self.selectIndexPath.row].imageUrl = transitionItem.imageUrl;
//    }
    [NvTimelineUtils resetTransition:self.timeline transitionDataArray:[[NvTimelineData sharedInstance] transitionDataArray]];
    
//    NvClipItem *item = self.clipDataSource[self.selectIndexPath.row];
    for (NvClipItem *item in self.clipDataSource) {
        if ([transitionItem.name isEqualToString:@"无"]) {
            item.transitionImageUrl = transitionItem.imageUrl;
        }else{
            if (transitionItem.builtinName.length != 0) {
                item.transitionImageUrl = [self getTransitionImageUrl:transitionItem.builtinName];
            }else{
                item.transitionImageUrl = [self getTransitionImageUrl:transitionItem.packageId];
            }
        }
    }
//    item.transitionImageUrl = [self getTransitionImageUrl:packageId];
    
    [self.clipCollectionView reloadData];
    [self seekTimeline:outpoint];
    int64_t transitions = (self.timeline.duration - outpoint)*1.0/NV_TIME_BASE;
    if (transitions > 2) {
        transitions = 2 * NV_TIME_BASE;
    }
    
    [self.liveWindowPanel playBackStart:self.liveWindowPanel.currentTime end:transitions + outpoint];
}

- (NSString *)getTransitionImageUrl:(NSString *)packageId {
    for (NvTransitionItem *item in self.transitionDataSource) {
        if ([item.packageId isEqualToString:packageId]) {
            return item.imageUrl;
        }
    }
    return nil;
}

/// MARK: UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView == self.clipCollectionView) {
        return self.clipDataSource.count;
    } else {
        return self.transitionDataSource.count;
    }
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.clipCollectionView) {
        NvClipCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NvClipCollectionViewCell" forIndexPath:indexPath];
        [cell renderCellWithClipItem:self.clipDataSource[indexPath.row]];
        [cell.transitionButton addTarget:self action:@selector(transitionButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        cell.transitionButton.tag = 1000 + indexPath.item;
        return cell;
    } else {
        NvTransitionCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NvTransitionCollectionViewCell" forIndexPath:indexPath];
        [cell renderCellWithClipItem:self.transitionDataSource[indexPath.row]];
        return cell;
    }
}

- (void)transitionButtonClick:(UIButton *)sender{
    _isSelected = YES;
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag - 1000 inSection:0];
    for (NvClipItem *item in self.clipDataSource) {
        item.isSelect = NO;
    }
    //选中框
    NvClipItem *item = self.clipDataSource[indexPath.row];
    item.isSelect = YES;
    //记录当前选择的index
    self.selectIndexPath = indexPath;
    [self.clipCollectionView reloadData];
    NSArray *array = [[NvTimelineData sharedInstance] editDataArray];
    // 没次都从inpoint的前0.5秒运行
    outpoint = [NvTimelineUtils getClipOutpoint:self.timeline clipInfo:array[indexPath.row]];
    outpoint = outpoint - 0.5*NV_TIME_BASE;
    if (outpoint <= 0) {
        outpoint = 0;
    } else if (outpoint >= self.timeline.duration) {//如果大于终点位置则从最开始播放
        outpoint = 0;
    }
    [self seekTimeline:outpoint];
    int64_t transitions = (self.timeline.duration - outpoint)*1.0/NV_TIME_BASE;
    if (transitions > 2) {
        transitions = 2 * NV_TIME_BASE;
    }

    [self.liveWindowPanel playBackStart:self.liveWindowPanel.currentTime end:transitions + outpoint];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.clipCollectionView) {
        NSArray *array = [[NvTimelineData sharedInstance] editDataArray];
        inPoint = [NvTimelineUtils getClipInpoint:self.timeline clipInfo:array[indexPath.row]];
        [self seekTimeline:inPoint];
        [self.liveWindowPanel playBackStart:self.liveWindowPanel.currentTime end:self.timeline.duration];
        //        for (NvClipItem *item in self.clipDataSource) {
        //            item.isSelect = NO;
        //        }
        //        //选中框
        //        NvClipItem *item = self.clipDataSource[indexPath.row];
        //        item.isSelect = YES;
        //        //记录当前选择的index
        //        self.selectIndexPath = indexPath;
        //        [self.clipCollectionView reloadData];
        //        NSArray *array = [[NvTimelineData sharedInstance] editDataArray];
        //        // 没次都从inpoint的前0.5秒运行
        //        outpoint = [NvTimelineUtils getClipOutpoint:self.timeline clipInfo:array[indexPath.row]];
        //        outpoint = outpoint - 0.5*NV_TIME_BASE;
        //        if (outpoint <= 0) {
        //            outpoint = 0;
        //        } else if (outpoint >= self.timeline.duration) {//如果大于终点位置则从最开始播放
        //            outpoint = 0;
        //        }
        //        [self seekTimeline:outpoint];
    } else {
        for (NvTransitionItem *item in self.transitionDataSource) {
            item.isSelect = NO;
        }
        NvTransitionItem *item = self.transitionDataSource[indexPath.row];
        item.isSelect = YES;
        [self.transitionCollectionView reloadData];
        //设置转场
        [self setTransitionWithId:item];
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.clipCollectionView) {
        if (indexPath.row == self.clipDataSource.count-1) {
            return CGSizeMake(77*SCREANSCALE, 48*SCREANSCALE);
        } else {
            return CGSizeMake(107*SCREANSCALE, 48*SCREANSCALE);
        }
    } else {
        return CGSizeMake(77*SCREANSCALE, 78*SCREANSCALE);
    }
}

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

@end
