//
//  EZMultiChannelRealPlayVC.m
//  EZOpenSDKDemo
//
//  Created by yuqian on 2020/3/10.
//  Copyright © 2020 hikvision. All rights reserved.
//

#import "EZMultiChannelRealPlayVC.h"
#import "EZOnlineCameraCell.h"
#import "EZOfflineCameraCell.h"
#import "EZEncryptCameraCell.h"
#import "EZDeviceInfo.h"
#import "EZCameraInfo.h"
#import "UIAlertController+DeviceVerifyCodeBySerial.h"
#import "EZRealPlayViewController.h"

@interface EZMultiChannelRealPlayVC () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UICollectionViewFlowLayout * flowLayout;

@property (nonatomic, strong) NSArray *devices;
@property (nonatomic, strong) NSMutableArray *cameras;
@property (nonatomic, strong) NSMutableArray *playingCameras;
@property (nonatomic, assign) BOOL thumbMode;

@end

static NSString * identifier1 = @"EZOnlineCameraCell";
static NSString * identifier2 = @"EZOfflineCameraCell";
static NSString * identifier3 = @"EZEncryptCameraCell";

static CGFloat kMagin = 20.f;

@implementation EZMultiChannelRealPlayVC

- (instancetype)initWithDevices:(NSArray *)devices
{
    self = [super init];
    if (self) {
        [self gatherCamerasData:devices];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"多通道预览";
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks target:self action:@selector(resizeCollectionLayout)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    [self.view addSubview:self.collectionView];
}

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

    [self schedulePlayCameras];
}

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

    [self stopAllCameraPreview];
}

-(UICollectionView *)collectionView{

    if (!_collectionView) {

        self.flowLayout = [[UICollectionViewFlowLayout alloc]init];
        CGFloat itemWidth = (self.view.frame.size.width - 2 * kMagin);

        _flowLayout.itemSize = CGSizeMake(itemWidth, itemWidth * 9/16);
        _flowLayout.minimumLineSpacing = 10;
        _flowLayout.minimumInteritemSpacing = 10;
        _flowLayout.sectionInset = UIEdgeInsetsMake(kMagin, kMagin, kMagin, kMagin);

        _collectionView = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:_flowLayout];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.bounces = NO;
        _collectionView.backgroundColor = [UIColor whiteColor];
        [_collectionView registerClass:[EZOnlineCameraCell class] forCellWithReuseIdentifier:identifier1];
        [_collectionView registerClass:[EZOfflineCameraCell class] forCellWithReuseIdentifier:identifier2];
        [_collectionView registerClass:[EZEncryptCameraCell class] forCellWithReuseIdentifier:identifier3];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
    }
    return _collectionView;
}

- (NSMutableArray *)playingCameras
{
    if (!_playingCameras) {
        _playingCameras = [NSMutableArray arrayWithCapacity:5];
    }
    return _playingCameras;
}

#pragma mark - Fetch data

- (void) gatherCamerasData:(NSArray *)devices {
    
    self.devices = devices;
    self.cameras = [NSMutableArray arrayWithCapacity:5];
    
    for (EZDeviceInfo *deviceInfo in devices) {
        for (EZCameraInfo *cameraInfo in deviceInfo.cameraInfo)
        {
            cameraInfo.status = deviceInfo.status;
            cameraInfo.isEncrypt = deviceInfo.isEncrypt;
            [self.cameras addObject:cameraInfo];
        }
    }
}

#pragma mark - Action

- (void) resizeCollectionLayout
{
    
    self.thumbMode = !self.thumbMode;
       
    CGFloat itemWidth;
    if (self.thumbMode) {
        itemWidth = (self.view.frame.size.width - 3 * kMagin)/2;
        _flowLayout.itemSize = CGSizeMake(itemWidth, itemWidth * 9/16);
    }
    else {
        itemWidth = (self.view.frame.size.width - 2 * kMagin);
        _flowLayout.itemSize = CGSizeMake(itemWidth, itemWidth * 9/16);
    }

    [self.collectionView performBatchUpdates:^{

        [self.collectionView reloadData];
        
    } completion:^(BOOL finished) {
        [self schedulePlayCameras];
    }];
}

#pragma mark - CollectionView Delegate

- (NSInteger)collectionView:(nonnull UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _cameras.count;
}

- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {

    EZCameraInfo *camera = _cameras[indexPath.row];
    NSString *verifyCode = [[GlobalKit shareKit].deviceVerifyCodeBySerial objectForKey:camera.deviceSerial];
    
    if (camera.status == 1) {
        if (camera.isEncrypt && verifyCode.length == 0) {
            EZEncryptCameraCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier3 forIndexPath:indexPath];
            cell.deviceSerial = camera.deviceSerial;
            return cell;
        } else {
            EZOnlineCameraCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier1 forIndexPath:indexPath];
            return cell;
        }
    } else {
        EZOfflineCameraCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier2 forIndexPath:indexPath];
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    id cell = [collectionView cellForItemAtIndexPath:indexPath];
    EZCameraInfo *cameraInfo = _cameras[indexPath.row];
    
    if ([cell isKindOfClass:[EZEncryptCameraCell class]]) {
        __weak typeof(self) weakSelf = self;
        [UIAlertController showAlertWithDeviceSerial:cameraInfo.deviceSerial confirmBlock:^(NSString * _Nonnull code) {
            __strong typeof(weakSelf) strongSelf = weakSelf;
            if (code.length >= 6) {
                [collectionView reloadItemsAtIndexPaths:@[indexPath]];
                dispatch_async(dispatch_get_main_queue(),^{
                    [strongSelf schedulePlayCameras];
                });
            } else {
                [strongSelf.view makeToastCenter:@"请输入正确的验证码"];
            }
        }];
    } else if ([cell isKindOfClass:[EZOnlineCameraCell class]]) {
        EZRealPlayViewController *vc = [[EZRealPlayViewController alloc] init];
        vc.deviceInfo = [self getSelectedDeviceInfo:cameraInfo.deviceSerial];
        vc.cameraIndex = cameraInfo.cameraNo-1;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (!decelerate) {
        [self schedulePlayCameras];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSLog(@"Mulitplay ----- %s", __func__);
    [self schedulePlayCameras];
}

#pragma mark - Private Methods

- (EZDeviceInfo *)getSelectedDeviceInfo:(NSString *)deviceSerial {
    for (EZDeviceInfo *deviceInfo in _devices) {
        if ([deviceInfo.deviceSerial isEqualToString:deviceSerial]) {
            return deviceInfo;
        }
    }
    return nil;
}

- (void)schedulePlayCameras {
    [self clearOutsideCamera];
    for (UITableViewCell *cell in self.collectionView.visibleCells) {
        if ([cell isMemberOfClass:[EZOnlineCameraCell class]]) {
            EZOnlineCameraCell *onlineCameraCell = (EZOnlineCameraCell *)cell;
            NSIndexPath *indexPath = [self.collectionView indexPathForCell:onlineCameraCell];
            EZCameraInfo *camera = _cameras[indexPath.row];
            NSString *verifyCode = [[GlobalKit shareKit].deviceVerifyCodeBySerial objectForKey:camera.deviceSerial];
            
            if (!onlineCameraCell.isPlaying) {
                [onlineCameraCell startPlayWithDeviceSerial:camera.deviceSerial cameraNo:camera.cameraNo verifyCode:verifyCode];
            }
            
            if (![self.playingCameras containsObject:onlineCameraCell]) {
                [self.playingCameras addObject:onlineCameraCell];
            }
        }
    }
    NSLog(@"Mulitplay ----- after schedule ------ playingCameras :%@, visibleCells :%@", self.playingCameras, self.collectionView.visibleCells);
}

- (void)clearOutsideCamera {
    NSLog(@"Mulitplay ----- before clear ------ playingCameras :%@, visibleCells :%@", self.playingCameras, self.collectionView.visibleCells);
    
    NSEnumerator *enumerator = [self.playingCameras reverseObjectEnumerator];
    for (EZOnlineCameraCell *cell in enumerator) {
        if (![self.collectionView.visibleCells containsObject:cell]) {
            [cell stopPlay];

            if ([self.playingCameras containsObject:cell]) {
                [self.playingCameras removeObject:cell];
            }
        }
    }
    
    NSLog(@"Mulitplay ----- after clear ------ playingCameras :%@, visibleCells :%@", self.playingCameras, self.collectionView.visibleCells);
}

- (void)stopAllCameraPreview {
    for (EZOnlineCameraCell *cell in self.playingCameras) {
        [cell stopPlay];
    }
}

@end
