//
//  ERTCVideoMeetingViewController.m
//  ERTCDemo
//
//  Created by wangjinlong23 on 2022/5/11.
//

#import "ERTCVideoMeetingViewController.h"
#import <ERTC/ERTC.h>
#import "UIView+Toast.h"
#import "ERTCPlayerViewManager.h"
#import "ERTCVideoMembersViewController.h"
#import "ERTCBeautyConfigurationViewController.h"
#import "ERTCVideoMeetingManager.h"
#import "ERTCMeetingSettingViewController.h"
#import "ERTCMettingtMembersViewController.h"
#import "ERTCReachability.h"

@interface ERTCVideoMeetingViewController ()<VCS_PlayerViewDelegate,ERTCDelegate>


@property (nonatomic, assign) UIStatusBarStyle statusBarStyle;

@property (nonatomic, strong) ERTCReachability *internetReachability;
@property (nonatomic, assign) ERTCNetworkStatus networkStatus;

@end

@implementation ERTCVideoMeetingViewController

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


- (void)viewDidLoad {
    [super viewDidLoad];
    [UIApplication sharedApplication].idleTimerDisabled = YES;
    self.view.backgroundColor = [UIColor YSSystemBackgroundWhiteColor];
    [self setupUI];
    __weak __typeof(self)weakSelf = self;
    [[ERTCLog sharedInstance] enableFileLog];  // 打开文件log
    [[ERTCLog sharedInstance] enableConsoleLog];  // 打开控制台log
    [[ERTCVideoMeetingManager sharedInstance] removeAllRemoteUser];
    [self.vcs_player enterRoomWithRoomId:self.roomId userId:self.userId completionBlock:^(NSError * _Nonnull error) {
        if (error == nil) {
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            [ERTCPlayerViewManager sharedInstance].engine.delegate = strongSelf;
        } else {
            [self showMessage:error.localizedDescription];
        }
    }];
    
    //  - 添加通知的监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate) name:UIApplicationWillTerminateNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kERTCReachabilityChangedNotification object:nil];
    
    // 创建Reachability
    ERTCReachability *connect = [ERTCReachability reachabilityForInternetConnection];
    // 开始监控网络,若网络状态改变, 就会发出通知kReachabilityChangedNotification
    [connect startNotifier];
    self.internetReachability = connect;
    self.networkStatus = ERTCReachableUnknow;

}


/// 网络状态变化信息同步 1-断开 2-恢复 3-切换
- (void)reachabilityChanged:(NSNotification *)note {
    ERTCReachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass:[ERTCReachability class]]);
    ERTCNetworkStatus netStatus = [curReach currentReachabilityStatus];
    switch (netStatus) {
        case ERTCNotReachable:
        {
            self.networkStatus = ERTCNotReachable;
            [[ERTCPlayerViewManager sharedInstance].engine setNetworkChange:1];
            ERTCLogI(@"网络状态---断开网络");
            break;
        }
            
        case ERTCReachableViaWWAN:
        {
            if (self.networkStatus == ERTCNotReachable) {
                [[ERTCPlayerViewManager sharedInstance].engine setNetworkChange:2];
                ERTCLogI(@"网络状态---恢复使用流量");
            } else {
                [[ERTCPlayerViewManager sharedInstance].engine setNetworkChange:3];
                ERTCLogI(@"网络状态---切换使用流量");
            }
            self.networkStatus = ERTCReachableViaWWAN;
            break;
        }
        case ERTCReachableViaWiFi:
        {
            if (self.networkStatus == ERTCNotReachable) {
                [[ERTCPlayerViewManager sharedInstance].engine setNetworkChange:2];
                ERTCLogI(@"网络状态---恢复使用wifi");
            } else {
                [[ERTCPlayerViewManager sharedInstance].engine setNetworkChange:3];
                ERTCLogI(@"网络状态---切换使用wifi");
            }
            self.networkStatus = ERTCReachableViaWiFi;
            break;
        }
        default:
        {
            self.networkStatus = ERTCReachableUnknow;
            ERTCLogI(@"网络状态---未知网络");
        }
            break;
    }
}


#pragma mark - UIViewController Life Cycle
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
//    //禁用侧滑手势方法
//    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
//    self.statusBarStyle = [UIApplication sharedApplication].statusBarStyle;
//    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [self.vcs_player viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [self.vcs_player viewDidAppear:animated];
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self exitCurrentMeetingAlert:@"" completion:nil];
//     });
    
}


-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
//
//    [UIApplication sharedApplication].statusBarStyle = self.statusBarStyle;
//    //禁用侧滑手势方法
//    self.navigationController.interactivePopGestureRecognizer.enabled = YES;

    //退出当前页面，设置为竖屏
    [UIDevice ys_setOrientation:(UIInterfaceOrientationPortrait)];
    [self.vcs_player viewWillDisappear:animated];
    
}

-(void)viewSafeAreaInsetsDidChange
{
    [super viewSafeAreaInsetsDidChange];
    [self.vcs_player viewSafeAreaInsetsDidChange];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

-(BOOL)shouldAutorotate {
    return YES;
}

-(UIInterfaceOrientationMask)supportedInterfaceOrientations {
    UIInterfaceOrientationMask orientations = UIInterfaceOrientationMaskAllButUpsideDown;
    if ([UIDevice getIsIpad]) {
        orientations = UIInterfaceOrientationMaskAll;
    }
    NSLog(@"ViewController-%@ supportedInterfaceOrientations orientations:%d", [self class], (int)orientations);
    return orientations;
}

/** 程序进入后台的通知的事件监听 */
-(void)appEnterBackground{
    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
}

/** 程序被杀死 */
-(void)applicationWillTerminate{
    //  - 监听到 app 被杀死时候的回调....
    NSLog(@"应用被杀死");
    [[ERTCPlayerViewManager sharedInstance] exitRoom];
    [[ERTCVideoMeetingManager sharedInstance] exitRoom];
    [self.vcs_player exitMeeting];
}

#pragma mark - UIContentContainer
-(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    [self.vcs_player viewWillTransitionToSize:size];

    NSLog(@"Size.width:%f",size.width);
    
    
}

#pragma mark -initUI
- (void)setupUI {
    [self.view addSubview:self.vcs_player];
    self.vcs_player.roomId = self.roomId;
    [self.vcs_player ysmas_makeConstraints:^(YSMASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}


#pragma mark -VCS_PlayerViewDelegate
///退出房间
- (void)play_exitMeeting {
    [self showAlert:@"确认退出房间？" withSureAction:^{
        [[ERTCPlayerViewManager sharedInstance] exitRoom];
        [[ERTCVideoMeetingManager sharedInstance] exitRoom];
        [self.vcs_player exitMeeting];
        [self.navigationController popViewControllerAnimated:YES];
        
    } andCencelAction:^{
        ;
    }];
}

///美颜设置
-(void)play_beautySetting {
    ERTCBeautyConfigurationViewController *vc = [ERTCBeautyConfigurationViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

///成员管理
-(void)play_membersManager {
    ERTCMettingtMembersViewController *vc = [ERTCMettingtMembersViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

///设置
- (void)play_setting {
    ERTCMeetingSettingViewController *vc = [[ERTCMeetingSettingViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -public
- (void)showAlert:(NSString *)str withSureAction:(dispatch_block_t)sureAction andCencelAction:(dispatch_block_t)cancelAction
{
    UIAlertController *alter = [UIAlertController alertControllerWithTitle:str message:nil preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (sureAction) {
            sureAction();
        }
    }];
    //取消按钮的风格是取消， 并且一直在最下边，且只能有一个
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        if (cancelAction) {
            cancelAction();
        }
    }];
    
    [alter addAction:sure];
    [alter addAction:cancle];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:alter animated:YES completion:nil];
    });
 }

- (void)showAlert:(NSString *)alertStr withAction:(dispatch_block_t)block
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:alertStr
                                                                             message:nil
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的"
                                                       style:UIAlertActionStyleDestructive
                                                     handler:^(UIAlertAction * _Nonnull action) {
        if (block) {
            block();
        }
    }];
    [alertController addAction:okAction];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:alertController animated:YES completion:nil];
    });

}


- (void)showMessage:(NSString *)message
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.view makeToast:message duration:1.2 position:CSToastPositionCenter];
    });
}



#pragma mark-getter
- (ERTCPlayerView *)vcs_player{
    if (!_vcs_player) {
        _vcs_player = [ERTCPlayerView initWithAction_VCS_PlayerView];
        _vcs_player.userDelegate = self;
        _vcs_player.superViewController = self;
    }
    return _vcs_player;
}


@end
