//
//  EZP2pTestVC.m
//  EZOpenSDKDemo
//
//  Created by JuneCheng on 2022/6/9.
//  Copyright © 2022 hikvision. All rights reserved.
//

#import "EZP2pTestVC.h"

#import "EZDeviceInfo.h"

static CGFloat const kTableViewHeaderHeight = 45.f;

@interface EZP2pTestVC () {
    EZDeviceInfo *selectDevice;
    
    NSArray<NSString *> *processedPreconnectSerialArray;
    NSArray<NSString *> *toDoPreconnectSerialArray;
    
    NSTimer *_timer;
}
@property (nonatomic, strong) UILabel *lab_p2pInfo;///< p2p连接信息
@property (nonatomic, strong) UIButton *btn_connect;///< 连接
@property (nonatomic, strong) UIButton *btn_disconnect;///< 断开
@property (nonatomic, strong) UIButton *btn_isPreConSucceedAction;///< p2p预连接是否成功

@property (nonatomic, strong) NSArray<EZDeviceInfo *> *deviceArray;///< 设备列表

@end

@implementation EZP2pTestVC

#pragma mark - 生命周期

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"p2p测试";
    
    [self.view addSubview:self.btn_connect];
    [self.view addSubview:self.btn_disconnect];
    [self.view addSubview:self.btn_isPreConSucceedAction];
    self.tableView.frame = CGRectMake(0, 50, kScreenWidth, kContentViewHeight-50);
    [self getDeviceList];
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(refreshAction) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

- (void)viewWillDisappear:(BOOL)animated {
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

#pragma mark - Actions

/** 连接Action */
- (void)connectAction {
    if (!selectDevice) {
        [EZToast show:@"请先选择一个设备"];
        return;
    }
    [EZOPENSDK startP2PPreconnect:selectDevice.deviceSerial];
}

/** 断开连接Action */
- (void)disconnectAction {
    if (!selectDevice) {
        [EZToast show:@"请先选择一个设备"];
        return;
    }
    [EZOPENSDK clearP2PPreconnect:selectDevice.deviceSerial];
}

/** 设备p2p预连接是否成功Action */
- (void)isPreConnectionSucceedAction {
    if (!selectDevice) {
        [EZToast show:@"请先选择一个设备"];
        return;
    }
    BOOL isSuccess = [EZOPENSDK isPreConnectionSucceed:selectDevice.deviceSerial];
    [EZToast show:isSuccess ? @"Success" : @"Failed"];
}

/** 刷新Action */
- (void)refreshAction {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        processedPreconnectSerialArray = [EZOPENSDK getAllProcessedPreconnectSerials];
        toDoPreconnectSerialArray = [EZOPENSDK getAllToDoPreconnectSerials];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            self.lab_p2pInfo.text = [NSString stringWithFormat:@"p2p预连接设备数量：%lu\n正在排队的p2p预连接设备数量：%lu", (unsigned long)processedPreconnectSerialArray.count, (unsigned long)toDoPreconnectSerialArray.count];
        });
    });
}

#pragma mark - 交易

/** 获取设备列表接口 */
- (void)getDeviceList {
    [EZOPENSDK getDeviceList:0
                    pageSize:20
                  completion:^(NSArray *deviceList, NSInteger totalCount, NSError *error) {
        self.deviceArray = deviceList;
        [self refreshAction];
    }];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.deviceArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"previewCellIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        UITableViewCellStyle style = UITableViewCellStyleValue1;
        cell = [[UITableViewCell alloc] initWithStyle:style reuseIdentifier:cellIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    EZDeviceInfo *deviceInfo = self.deviceArray[indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@", kStringIsEmpty(deviceInfo.deviceName) ? [NSString stringWithFormat:@"%@(%@)", deviceInfo.category, deviceInfo.deviceSerial] : deviceInfo.deviceName];
    // 设置title颜色
    if ([processedPreconnectSerialArray containsObject:deviceInfo.deviceSerial]) {
        cell.textLabel.textColor = [UIColor orangeColor];
    } else {
        cell.textLabel.textColor = [UIColor blackColor];
    }
    // 设置选中状态
    if ([selectDevice.deviceSerial isEqualToString:deviceInfo.deviceSerial]) {
        cell.contentView.backgroundColor = [UIColor lightGrayColor];
    } else {
        cell.contentView.backgroundColor = [UIColor whiteColor];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kTableViewHeaderHeight;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kTableViewHeaderHeight)];
    [view addSubview:self.lab_p2pInfo];
    return view;
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    return @"橙色:p2p已连接或正在连接中  黑色:p2p未连接";
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSIndexPath *previousIndexPath = [NSIndexPath indexPathForRow:[self.deviceArray indexOfObject:selectDevice] inSection:0];
    selectDevice = self.deviceArray[indexPath.row];
    [tableView reloadRowsAtIndexPaths:@[previousIndexPath] withRowAnimation:UITableViewRowAnimationNone];
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark - 懒加载

- (UILabel *)lab_p2pInfo {
    if (!_lab_p2pInfo) {
        _lab_p2pInfo = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, kScreenWidth-20, kTableViewHeaderHeight)];
        _lab_p2pInfo.font = [UIFont systemFontOfSize:14.f];
        _lab_p2pInfo.textColor = [UIColor orangeColor];
        _lab_p2pInfo.numberOfLines = 0;
    }
    return _lab_p2pInfo;
}

- (UIButton *)btn_connect {
    if (!_btn_connect) {
        _btn_connect = [UIButton buttonWithType:UIButtonTypeCustom];
        _btn_connect.frame = CGRectMake(10, 10, 100, 40);
        [_btn_connect setBackgroundColor:[UIColor orangeColor]];
        [_btn_connect setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_btn_connect setTitle:@"连接" forState:UIControlStateNormal];
        _btn_connect.titleLabel.font = [UIFont systemFontOfSize:15.0];
        _btn_connect.layer.cornerRadius = 20.f;
        [_btn_connect addTarget:self action:@selector(connectAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btn_connect;
}

- (UIButton *)btn_disconnect {
    if (!_btn_disconnect) {
        _btn_disconnect = [UIButton buttonWithType:UIButtonTypeCustom];
        _btn_disconnect.frame = CGRectMake(120, 10, 100, 40);
        [_btn_disconnect setBackgroundColor:[UIColor orangeColor]];
        [_btn_disconnect setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_btn_disconnect setTitle:@"断开" forState:UIControlStateNormal];
        _btn_disconnect.titleLabel.font = [UIFont systemFontOfSize:15.0];
        _btn_disconnect.layer.cornerRadius = 20.f;
        [_btn_disconnect addTarget:self action:@selector(disconnectAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btn_disconnect;
}

- (UIButton *)btn_isPreConSucceedAction {
    if (!_btn_isPreConSucceedAction) {
        _btn_isPreConSucceedAction = [UIButton buttonWithType:UIButtonTypeCustom];
        _btn_isPreConSucceedAction.frame = CGRectMake(230, 10, 100, 40);
        [_btn_isPreConSucceedAction setBackgroundColor:[UIColor orangeColor]];
        [_btn_isPreConSucceedAction setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_btn_isPreConSucceedAction setTitle:@"预连接结果" forState:UIControlStateNormal];
        _btn_isPreConSucceedAction.titleLabel.font = [UIFont systemFontOfSize:15.0];
        _btn_isPreConSucceedAction.layer.cornerRadius = 20.f;
        [_btn_isPreConSucceedAction addTarget:self action:@selector(isPreConnectionSucceedAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btn_isPreConSucceedAction;
}

@end
