//
//  ERTCMembersNetworkInfoView.m
//  EZSaaSVideoConferenceSDK
//
//  Created by wangjinlong23 on 2022/6/23.
//  Copyright © 2022 EZSaaS. All rights reserved.
//

#import "ERTCMembersNetworkInfoView.h"
#import <ERTC/ERTCStatistics.h>
#import "ERTCMembersNetworkManager.h"
#import "ERTCVideoMeetingManager.h"
#import "ERTCMemberNetworkSendAudioTitleCell.h"
#import "ERTCMemberNetworkSendVideoTitleCell.h"
#import "ERTCMemberNetworkReceiveAudioTitleCell.h"
#import "ERTCMemberNetworkReceiveVideoTitleCell.h"
#import "ERTCMemberNetworkScreenShareTitleCell.h"
#import "ERTCMemberNetworkSendAudioContentCell.h"
#import "ERTCMemberNetworkSendVideoContentCell.h"
#import "ERTCMemberNetworkReceiveAudioContentCell.h"
#import "ERTCMemberNetworkReceiveVideoContentCell.h"
#import "ERTCMemberNetworkShareScreenContentCell.h"

@interface ERTCMembersNetworkInfoView ()<UITableViewDelegate, UITableViewDataSource,ERTCMembersNetworkManagerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UILabel *headerContentLabel;

@property (nonatomic, strong) NSMutableArray<NSString *> *sectionTitles;
@property (nonatomic, strong) NSMutableArray<NSMutableArray<NSMutableDictionary *> *> *dataSource;

@property (nonatomic, strong) ERTCLocalAudioStatistics *localAudioStats;//本地音频数据
//@property (nonatomic, strong) ERTCLocalVideoStatistics *localVideoStats;//本地视频数据

@property (nonatomic, strong) NSArray *localVideoArray;//本地视频数据
@property (nonatomic, strong) NSArray *remoteAudioArray;//远端音频数据
@property (nonatomic, strong) NSArray *remoteVideoArray;//远端视频数据

@end

@implementation ERTCMembersNetworkInfoView

-(instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.65];
        [self setUpUI];
        [ERTCMembersNetworkManager sharedInstance].delegate = self;
        [self resetDataSource];
    }
    
    return self;
}

-(void)closeView {
    self.hidden = YES;
    [self removeFromSuperview];
}

#pragma mark -ERTCMembersNetworkManagerDelegate
- (void)onLocalAudioStats:(ERTCLocalAudioStatistics *)audioStats {
    self.localAudioStats = audioStats;
    [self resetDataSource];
    [self.tableView reloadData];
}

- (void)onLocalVideoStats:(NSMutableDictionary *)videoStats {
    self.localVideoArray = [videoStats allValues];
    [self resetDataSource];
    [self.tableView reloadData];
}

- (void)onRemoteAudioUpdate:(NSMutableDictionary *)data {
    self.remoteAudioArray = [data allValues];
    [self resetDataSource];
    [self.tableView reloadData];
}

- (void)onRemoteVideoUpdate:(NSMutableDictionary *)data {
    self.remoteVideoArray = [data allValues];
    [self resetDataSource];
    [self.tableView reloadData];
}
#pragma mark - DataSource
-(void)resetDataSource {
    self.dataSource = [NSMutableArray array];
    self.sectionTitles = [NSMutableArray array];
    NSMutableArray *array = [NSMutableArray array];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    CGFloat height = 0;
    
    //屏幕共享发送端
    array = [NSMutableArray array];
    dict = [NSMutableDictionary dictionary];
    [dict setObject:[ERTCMemberNetworkSendVideoTitleCell cellReuseId] forKey:@"cellId"];
    height = [ERTCMemberNetworkSendVideoTitleCell heightForCell];
    [dict setObject:@(height) forKey:@"height"];
    [array addObject:dict];
    [self.localVideoArray enumerateObjectsUsingBlock:^(ERTCLocalVideoStatistics *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.videoStreamType == 2) {
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            [dict setObject:[ERTCMemberNetworkSendVideoContentCell cellReuseId] forKey:@"cellId"];
            [dict setObject:obj forKey:@"object"];
            CGFloat height = 50;
            [dict setObject:@(height) forKey:@"height"];
            [array addObject:dict];
        }
    }];
    
    [self.dataSource addObject:array];
    [self.sectionTitles addObject:@"屏幕共享发送端"];
    
    //屏幕共享接收端
    array = [NSMutableArray array];
    dict = [NSMutableDictionary dictionary];
    [dict setObject:[ERTCMemberNetworkScreenShareTitleCell cellReuseId] forKey:@"cellId"];
    height = [ERTCMemberNetworkScreenShareTitleCell heightForCell];
    [dict setObject:@(height) forKey:@"height"];
    [array addObject:dict];
    [self.remoteVideoArray enumerateObjectsUsingBlock:^(ERTCRemoteVideoStatistics *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        ERTCUserInfo *info = [[ERTCVideoMeetingManager sharedInstance] getMemberInfoByUserId:obj.userId];
            if (obj.streamType == 2 && info.isSharingAccount) {
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                [dict setObject:[ERTCMemberNetworkShareScreenContentCell cellReuseId] forKey:@"cellId"];
                [dict setObject:obj forKey:@"object"];
                CGFloat height = 50;
                [dict setObject:@(height) forKey:@"height"];
                [array addObject:dict];
        }
    }];
    [self.dataSource addObject:array];
    [self.sectionTitles addObject:@"屏幕共享接收端"];
   
    
    
    //本地音频
    array = [NSMutableArray array];
    dict = [NSMutableDictionary dictionary];
    [dict setObject:[ERTCMemberNetworkSendAudioTitleCell cellReuseId] forKey:@"cellId"];
    height = [ERTCMemberNetworkSendAudioTitleCell heightForCell];
    [dict setObject:@(height) forKey:@"height"];
    [array addObject:dict];
    
    if (self.localAudioStats != nil) {
        dict = [NSMutableDictionary dictionary];
        [dict setObject:[ERTCMemberNetworkSendAudioContentCell cellReuseId] forKey:@"cellId"];
        [dict setObject:self.localAudioStats forKey:@"object"];
        height = 50;
        [dict setObject:@(height) forKey:@"height"];
        [array addObject:dict];
    }
    [self.dataSource addObject:array];
    [self.sectionTitles addObject:@"发送音频"];
    
    //本地视频
    array = [NSMutableArray array];
    dict = [NSMutableDictionary dictionary];
    [dict setObject:[ERTCMemberNetworkSendVideoTitleCell cellReuseId] forKey:@"cellId"];
    height = [ERTCMemberNetworkSendVideoTitleCell heightForCell];
    [dict setObject:@(height) forKey:@"height"];
    [array addObject:dict];
    [self.localVideoArray enumerateObjectsUsingBlock:^(ERTCLocalVideoStatistics *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:[ERTCMemberNetworkSendVideoContentCell cellReuseId] forKey:@"cellId"];
        [dict setObject:obj forKey:@"object"];
        CGFloat height = 50;
        [dict setObject:@(height) forKey:@"height"];
        [array addObject:dict];
    }];
    
    [self.dataSource addObject:array];
    [self.sectionTitles addObject:@"发送视频"];
    
    //远端音频
    array = [NSMutableArray array];
    dict = [NSMutableDictionary dictionary];
    [dict setObject:[ERTCMemberNetworkReceiveAudioTitleCell cellReuseId] forKey:@"cellId"];
    height = [ERTCMemberNetworkReceiveAudioTitleCell heightForCell];
    [dict setObject:@(height) forKey:@"height"];
    [array addObject:dict];
    [self.remoteAudioArray enumerateObjectsUsingBlock:^(ERTCRemoteAudioStatistics *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        ERTCUserInfo *info = [[ERTCVideoMeetingManager sharedInstance] getMemberInfoByUserId:obj.userId];
        if (info.uid.length > 0 && info.isAudioAvailable) {
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            [dict setObject:[ERTCMemberNetworkReceiveAudioContentCell cellReuseId] forKey:@"cellId"];
            [dict setObject:obj forKey:@"object"];
            CGFloat height = 50;
            [dict setObject:@(height) forKey:@"height"];
            [array addObject:dict];
        }
    }];
    
    [self.dataSource addObject:array];
    [self.sectionTitles addObject:@"接收音频"];
    
    //远端视频
    array = [NSMutableArray array];
    dict = [NSMutableDictionary dictionary];
    [dict setObject:[ERTCMemberNetworkReceiveVideoTitleCell cellReuseId] forKey:@"cellId"];
    height = [ERTCMemberNetworkReceiveVideoTitleCell heightForCell];
    [dict setObject:@(height) forKey:@"height"];
    [array addObject:dict];
    [self.remoteVideoArray enumerateObjectsUsingBlock:^(ERTCRemoteVideoStatistics *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        ERTCUserInfo *info = [[ERTCVideoMeetingManager sharedInstance] getMemberInfoByUserId:obj.userId];
        if (info.uid.length > 0 && info.isVideoAvailable) {
            if (obj.streamType != 2) {
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                [dict setObject:[ERTCMemberNetworkReceiveVideoContentCell cellReuseId] forKey:@"cellId"];
                [dict setObject:obj forKey:@"object"];
                CGFloat height = 50;
                [dict setObject:@(height) forKey:@"height"];
                [array addObject:dict];
            }
        }
        
    }];
    [self.dataSource addObject:array];
    [self.sectionTitles addObject:@"接收视频"];
    [self.tableView reloadData];
}

#pragma mark - UITableViewDelegate UITableViewDataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 
    NSArray *rows = self.dataSource[indexPath.section];
    NSDictionary *dict = rows[indexPath.row];
    NSString *value = dict[@"object"];
    NSString *cellId = dict[@"cellId"];
    UITableViewCell *viewcell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    if ([viewcell isKindOfClass:[ERTCMemberNetworkSendAudioContentCell class]]) {
        ERTCMemberNetworkSendAudioContentCell *cell = (ERTCMemberNetworkSendAudioContentCell *)viewcell;
        if ([value isKindOfClass:[ERTCLocalAudioStatistics class]]) {
            ERTCLocalAudioStatistics *info = (ERTCLocalAudioStatistics *)value;
            cell.localAudioStats = info;
        }
    } else if ([viewcell isKindOfClass:[ERTCMemberNetworkSendVideoContentCell class]]) {
        ERTCMemberNetworkSendVideoContentCell *cell = (ERTCMemberNetworkSendVideoContentCell *)viewcell;
        if ([value isKindOfClass:[ERTCLocalVideoStatistics class]]) {
            ERTCLocalVideoStatistics *info = (ERTCLocalVideoStatistics *)value;
            cell.localVideoStats = info;
        }
    } else if ([viewcell isKindOfClass:[ERTCMemberNetworkReceiveAudioContentCell class]]) {
        ERTCMemberNetworkReceiveAudioContentCell *cell = (ERTCMemberNetworkReceiveAudioContentCell *)viewcell;
        if ([value isKindOfClass:[ERTCRemoteAudioStatistics class]]) {
            ERTCRemoteAudioStatistics *info = (ERTCRemoteAudioStatistics *)value;
            cell.remoteAudioStats = info;
        }
    } else if ([viewcell isKindOfClass:[ERTCMemberNetworkReceiveVideoContentCell class]]) {
        ERTCMemberNetworkReceiveVideoContentCell *cell = (ERTCMemberNetworkReceiveVideoContentCell *)viewcell;
        if ([value isKindOfClass:[ERTCRemoteVideoStatistics class]]) {
            ERTCRemoteVideoStatistics *info = (ERTCRemoteVideoStatistics *)value;
            cell.remoteVideoStats = info;
        }
    } else if ([viewcell isKindOfClass:[ERTCMemberNetworkShareScreenContentCell class]]) {
        ERTCMemberNetworkShareScreenContentCell *cell = (ERTCMemberNetworkShareScreenContentCell *)viewcell;
        if ([value isKindOfClass:[ERTCRemoteVideoStatistics class]]) {
            ERTCRemoteVideoStatistics *info = (ERTCRemoteVideoStatistics *)value;
            cell.remoteVideoStats = info;
        }
    }

    viewcell.selectionStyle = UITableViewCellSelectionStyleNone;
    return viewcell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *rows = self.dataSource[indexPath.section];
    NSDictionary *dict = rows[indexPath.row];
    CGFloat height = [dict[@"height"] floatValue];
    return height;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *rows = self.dataSource[section];
    return rows.count;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] init];
    UILabel *headerLabel = [[UILabel alloc] init];
    headerLabel.backgroundColor = [UIColor clearColor];
    headerLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:20];
    headerLabel.textColor = [UIColor whiteColor];

    [headerView addSubview:headerLabel];
    [headerLabel ysmas_makeConstraints:^(YSMASConstraintMaker *make) {
        make.centerY.equalTo(headerView);
        make.left.equalTo(kSafeMasLeft(headerView));//.with.offset(20);
    }];
    
    headerLabel.text = self.sectionTitles[section];
    
    return headerView;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [UIView new];
    return view;
}

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

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0;
}

#pragma mark - Private Method
-(void)setUpUI {
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"质量监测";
    titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:19];
    titleLabel.textColor = [UIColor whiteColor];
    [self addSubview:titleLabel];
    
    UIView *historyTapView = [UIView new];
    historyTapView.backgroundColor = [UIColor clearColor];
    
    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeView)];
    [historyTapView addGestureRecognizer:tapGes];
    [self addSubview:historyTapView];
    [self addSubview:self.tableView];
    
    UIImageView *historyBtnLabel = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icn_close_search_bg"]];
    [historyTapView addSubview:historyBtnLabel];
    [historyBtnLabel ysmas_makeConstraints:^(YSMASConstraintMaker *make) {
        make.center.equalTo(historyTapView);
    }];
    
    [titleLabel ysmas_makeConstraints:^(YSMASConstraintMaker *make) {
        make.top.equalTo(self).with.offset(50);
        make.left.equalTo(kSafeMasLeft(self)).with.offset(10);
    }];
    
    [historyTapView ysmas_makeConstraints:^(YSMASConstraintMaker *make) {
        make.centerY.equalTo(titleLabel);
        make.right.equalTo(self).with.offset(-20);
        make.width.height.ysmas_equalTo(50);
    }];
    
    [self.tableView ysmas_makeConstraints:^(YSMASConstraintMaker *make) {
        make.top.equalTo(titleLabel.ysmas_bottom).with.offset(20);
        make.left.equalTo(self).with.offset(10);
        make.right.equalTo(self).with.offset(-10);
        make.bottom.equalTo(self).with.offset(-50);
    }];
}

#pragma mark - Getter Method
-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [_tableView registerClass:[ERTCMemberNetworkSendAudioTitleCell class]
           forCellReuseIdentifier:[ERTCMemberNetworkSendAudioTitleCell cellReuseId]];
        [_tableView registerClass:[ERTCMemberNetworkSendVideoTitleCell class]
           forCellReuseIdentifier:[ERTCMemberNetworkSendVideoTitleCell cellReuseId]];
        [_tableView registerClass:[ERTCMemberNetworkReceiveAudioTitleCell class]
           forCellReuseIdentifier:[ERTCMemberNetworkReceiveAudioTitleCell cellReuseId]];
        [_tableView registerClass:[ERTCMemberNetworkReceiveVideoTitleCell class]
           forCellReuseIdentifier:[ERTCMemberNetworkReceiveVideoTitleCell cellReuseId]];
        [_tableView registerClass:[ERTCMemberNetworkSendAudioContentCell class]
           forCellReuseIdentifier:[ERTCMemberNetworkSendAudioContentCell cellReuseId]];
        [_tableView registerClass:[ERTCMemberNetworkSendVideoContentCell class]
           forCellReuseIdentifier:[ERTCMemberNetworkSendVideoContentCell cellReuseId]];
        [_tableView registerClass:[ERTCMemberNetworkReceiveAudioContentCell class]
           forCellReuseIdentifier:[ERTCMemberNetworkReceiveAudioContentCell cellReuseId]];
        [_tableView registerClass:[ERTCMemberNetworkReceiveVideoContentCell class]
           forCellReuseIdentifier:[ERTCMemberNetworkReceiveVideoContentCell cellReuseId]];
        [_tableView registerClass:[ERTCMemberNetworkScreenShareTitleCell class] forCellReuseIdentifier:[ERTCMemberNetworkScreenShareTitleCell cellReuseId]];
        [_tableView registerClass:[ERTCMemberNetworkShareScreenContentCell class] forCellReuseIdentifier:[ERTCMemberNetworkShareScreenContentCell cellReuseId]];
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.rowHeight = 66;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor clearColor];
    }
    
    return _tableView;
}

-(void)dealloc {
    NSLog(@"%@ dealloc", [self class]);
}

@end
