//
//  RTCVideoCallViewController.m
//  simple_rtc_ios
//
//  Created by v_liyingna on 3/14/23.
//

#import "RTCVideoCallViewController.h"
#import <BaiduRtcRoom/BaiduRtcRoom.h>
#import "BDCloudRTCBaseDefine.pch"
#import "RTCVideoCallView.h"
#import "UserRemoteManager.h"

@interface RTCVideoCallViewController ()<RTCVideoCallViewDelegate, BaiduRtcRoomDelegate>
@property (nonatomic, readonly) RTCVideoCallView *videoCallView;
@property (nonatomic, copy) NSString *roomName;
@property (nonatomic, assign)  NSInteger userId;
@property (nonatomic, copy) NSString *appId;
@property (nonatomic, copy) NSString *tokenStr;
@property (nonatomic, strong) NSArray<NSNumber *> *streamingIds;
@property (nonatomic, assign) BOOL isWatch;
@property (nonatomic, assign) BOOL isSubscribedStreaming;
@property (nonatomic, strong) BaiduRtcRoomApi *rtcRoomApi;
@property (nonatomic, assign) BOOL isMultiPersons;
@property (nonatomic, assign) BOOL bShowStates;
@property (nonatomic, copy) NSString *signalServerUrl;
@property (nonatomic, copy) NSString *mediaServerIp;
@property (nonatomic, assign) BOOL ismuteMicphone;
@property (nonatomic, assign) BOOL ismuteCamera;
@property (nonatomic, assign) BOOL isSwitchSpeaker;

@property (nonatomic, strong) RTCVideoUserInfoView *localUserInfoView;

@end

@implementation RTCVideoCallViewController

- (void)dealloc {
    [[UserRemoteManager instance] remoteAllRemove];
    [self.rtcRoomApi logoutRtcRoom];
}

- (instancetype)initForRoom:(NSString *)room
                     userId:(NSString *)userId
                    isWatch:(BOOL)isWatch
                   delegate:(id<RTCVideoCallViewControllerDelegate>)delegate {
    if (self = [super init]) {
        _delegate = delegate;
        self.isSwitchSpeaker = YES;
        self.isWatch = isWatch;
        self.userId = [userId integerValue];
        NSLog(@"vocs Login room with userID: %ld", (long)self.userId);
        self.roomName = room;

        self.appId = BDCloudDefaultRTCAppID;
        self.tokenStr = BDCloudDefaultRTCAppToken;
        [BaiduRtcRoomApi setVerbose:YES];
    }
    return self;
    
}

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

- (void)viewDidLoad {
    // app从后台进入前台都会调用这个方法
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive) name:UIApplicationWillResignActiveNotification object:nil];

}

- (void)call {
    self.rtcRoomApi = [[BaiduRtcRoomApi alloc] initSDKWithAppID:self.appId
                                                           tokenStr:self.tokenStr
                                                           delegate:self];

    RtcParameterSettings *rps = [[RtcParameterSettings alloc] init];
    if (self.isWatch) {
        /** 采集分辨率 288x352 */
        RtcVideoBaseParams *captureParams = [[RtcVideoBaseParams alloc] init];
        captureParams.videoFps = 6;
        captureParams.videoWidth = 288;
        captureParams.videoHeight = 352;
        rps.videoCaptureParams = captureParams;
        
        /** 编码分辨率 240x280 */
        RtcVideoEncodeParams *videoParams = [[RtcVideoEncodeParams alloc] init];
        videoParams.videoFps = 6;
        videoParams.videoWidth = 240;
        videoParams.videoHeight = 280;

        videoParams.videoBitrate = 500;
        videoParams.videoMinBitrate = 300;
        videoParams.videoCodecType = RTC_VIDEO_ENCODE_TYPE_JPEG;
        rps.videoEncodeParams = @{
            RTC_MEDIA_TARGET_VIDEO_DEFAULT: videoParams
        };
        
        rps.isEnableFixedResolution = YES;
        rps.netEqMaxDelay = 400;
        rps.audioCodecType = RTC_AUDIO_ENCODE_TYPE_PCMU;
        rps.signalChannelMode = RTC_SIGNAL_CHANNEL_MODE_QUIC;
        rps.isEnableFec = false;
        rps.audioLevelEnable = false;
     
    }
    [self.rtcRoomApi setParamSettings:rps paramType:RTC_PARAM_SETTINGS_ALL];

    //前置摄像头
    [self.rtcRoomApi setCameraFace:YES];
    //设置扬声器
    [self.rtcRoomApi presetLoudSpeaker:_isSwitchSpeaker];
    //设置本地预览
    [self.rtcRoomApi setLocalDisplay:_videoCallView.localVideoView];
    [_videoCallView.localVideoView.videoView addSubview:self.localUserInfoView];
    [self.localUserInfoView setupUserId:self.userId];
    _videoCallView.localVideoView.videoView.hidden = NO;
    //登录房间
    [self.rtcRoomApi loginRtcRoomWithRoomName:self.roomName
                                           userID:self.userId
                                      displayName:@"James"];
}

- (void)loadView {
    _videoCallView = [[RTCVideoCallView alloc] initWithFrame:CGRectZero
                                                     isWatch:self.isWatch
                                                         uid:self.userId
                                                  sdkVersion:[BaiduRtcRoomApi version]];
    _videoCallView.delegate = self;
    _videoCallView.roomInfoLabel.text = [NSString stringWithFormat:@"房间号：%@", self.roomName];
    _videoCallView.statusLabel.text = [self statusTextForState:RTC_CONNECTION_STATE_CONNECTING];
    [_videoCallView updateRouteChangeStatus:self.isSwitchSpeaker];

    self.view = _videoCallView;
    [self call];
}

- (void)applicationBecomeActive {
    [self.rtcRoomApi enableLocalAudio:YES];
    [self.rtcRoomApi muteMicphone:_ismuteMicphone];
}

- (void)applicationWillResignActive {
    [self.rtcRoomApi enableLocalAudio:NO];
    [self.rtcRoomApi muteMicphone:YES];
}

#pragma mark BaiduRtcRoomDelegate

- (void)onRemoteUserJoinRoom:(NSInteger)uid userName:(NSString *)userName {
    NSLog(@"onRemoteUserJoinRoom user joined: %ld, name:%@", uid, userName);
    NSLog(@"Userevents user joined: %ld...", uid);
    //动态分配显示的view 按照id分配显示
    [[UserRemoteManager instance] remoteUserJoin:uid];
}
- (void)onRemoteUserLeaveRoom:(NSInteger)uid userName:(NSString *)userName {
    NSLog(@"Userevents user leaving: %ld...", uid);
    [[UserRemoteManager instance] remoteUserLeave:uid];
}
- (void)onError:(NSInteger)errCode errMsg:(NSString *)errMsg extInfo:(NSDictionary *)extInfo {
    NSLog(@"onError, code:%d, msg:%@, %@", (int)errCode, errMsg, extInfo);
    [self showAlertWithMessage:errMsg];
}
- (void)onWarning:(NSInteger)warningCode warningMsg:(NSString *)warnMsg extInfo:(NSDictionary *)extInfo {
    NSLog(@"onWarning, code:%d, msg:%@, %@", (int)warningCode, warnMsg, extInfo);
}
- (void)onFirstVideoFrame:(NSInteger)uid width:(int)width height:(int)height {
    NSLog(@"onFirstVideoFrame, uid:%ld ,%dx%d", uid, width, height);
}
- (void)onConnectionStateChanged:(NSInteger)state reason:(NSInteger)reason {
    NSLog(@"onConnectionStateChanged, state:%ld, reason:%ld", state, reason);
    __weak RTCVideoCallViewController *weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        RTCVideoCallViewController *strongSelf = weakSelf;
        strongSelf.videoCallView.statusLabel.text =
        [strongSelf statusTextForState:state];
    });
    
    if (state == RTC_CONNECTION_STATE_CONNECTED) {
        NSLog(@"onConnectionStateChanged connected!");
    }
}
- (void)onRemoteUserVideoAvailable:(NSInteger)uid desc:(NSString *)desc available:(BOOL)available {
    NSLog(@"onRemoteUserVideoAvailable, uid:%ld, desc:%@, available:%d", uid, desc, available);
}

- (void)onRemoteUserAudioAvailable:(NSInteger)uid desc:(NSString *)desc available:(BOOL)available {
    NSLog(@"onRemoteUserAudioAvailable, uid:%ld, desc:%@, available:%d", uid, desc, available);
}

- (void)onSendMediaState:(BRTCMediaType)type state:(int)state {
    NSLog(@"onSendMediaState, type:%ld, state:%d", type, state);
}


- (void)onVideoStreamChangedState:(NSInteger)uid userName:(NSString *)userName desc:(NSString *)desc state:(NSInteger)state {
    NSLog(@"onVideoStreamChangedState, uid:%ld, name:%@, desc:%@, state:%d", uid, userName, desc, (int)state);
    if (state == RTC_STREAM_ADD) {
        if ([desc isEqualToString:RTC_MEDIA_TARGET_VIDEO_DEFAULT] || [desc isEqualToString:RTC_MEDIA_TARGET_AUDIO_DEFAULT]) {
            
            RTCRemoteVideoViewInfo *videoInfo = [[UserRemoteManager instance] remoteUserQuery:uid];
            if (videoInfo) {
                [self.rtcRoomApi setRemoteDisplay:videoInfo.videoView userId:uid];
                videoInfo.videoView.userId = uid;
            }
            // 更新视图 uid
            [self setupUserID];
            [[UserRemoteManager instance] remoteUserSubStatus:uid subscribe:YES];
            //重新布局UI 在 videoCallView中实现的
            [self.videoCallView updateSubView:videoInfo.videoView uid:videoInfo.videoView.userId add:YES];
        }
        
    } else if (state == RTC_STREAM_REMOVE) {
        // 屏幕流在流到达状态变化时独立处理视图
        if ([desc isEqualToString:RTC_MEDIA_TARGET_VIDEO_DEFAULT] || [desc isEqualToString:RTC_MEDIA_TARGET_AUDIO_DEFAULT]) {
            RTCRemoteVideoViewInfo *videoInfo = [[UserRemoteManager instance] remoteUserQuery:uid];
            if (!videoInfo) {
                return;
            }

            if (videoInfo.videoView.videoView) {
                [videoInfo.videoView.videoView removeFromSuperview]; //从主页面移除
            }
            [[UserRemoteManager instance] remoteUserSubStatus:uid subscribe:NO];
            [self.videoCallView updateSubView:videoInfo.videoView uid:uid add:NO];

        }
    }

}

- (void)onAudioStreamChangedState:(NSInteger)uid userName:(NSString *)userName desc:(NSString *)desc state:(NSInteger)state {
    NSLog(@"onAudioStreamChangedState, uid:%ld, name:%@, desc:%@, state:%d", uid, userName, desc, (int)state);
}



/**
 RTC引擎状态信息统计
 
 @param statistics rtc引擎状态信息统计数组
 @discussion 该callback返回当前rtc engine的一些参数和性能信息，如传输fps,码率，网络状况,cpu等信息给app
 */
- (void)onEngineStatisticsInfo:(NSArray *)statistics {
    NSLog(@"onEngineStatisticsInfo = %@", statistics);
}

- (NSArray *)rtcViewQueryUserListOfRoom {
    return [self.rtcRoomApi queryMessageUserListOfRoom];
}

- (void)setupUserID {
    [self.localUserInfoView setupUserId:self.userId];
    
    NSArray *arr = [[UserRemoteManager instance] remoteSubScribedUsers];
    for (RTCRemoteVideoViewInfo *videoInfo in arr) {
        if (!videoInfo.videoView) continue;
        [videoInfo.userInfoView setupUserId:videoInfo.videoView.userId];
    }
}

- (void)showAlertWithMessage:(NSString*)message {
    UIAlertController *alert =
    [UIAlertController alertControllerWithTitle:nil
                                        message:message
                                 preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK"
                                                            style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction *action){
                                                          }];
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - RTCVideoCallViewDelegate
- (void)videoCallViewDidRemoteviewDisappear:(BOOL)disappear remoteUid:(NSString*)userId {
    [self.rtcRoomApi setRemoteVideoPlayState:!disappear userId:[userId longLongValue]];
}

- (void)videoCallAudoDidRemoteviewDisappear:(BOOL)disappear remoteUid:(NSString*)userId {
    [self.rtcRoomApi setRemoteAudioPlayState:!disappear userId:[userId longLongValue]];
}

- (void)videoCallViewDidMuteMicphone:(RTCVideoCallView *)view {
    _ismuteMicphone = !_ismuteMicphone;
    [self.rtcRoomApi muteMicphone:_ismuteMicphone];
}

- (void)videoCallViewDidHangup:(RTCVideoCallView *)view {
    NSLog(@"Click hangup botton!");
    [self hangup];
}

- (void)videoCallViewDidSwitchCamera:(RTCVideoCallView *)view {
    [self.rtcRoomApi switchCamera];
}

- (void)videoCallViewDidMuteCamera:(RTCVideoCallView *)view mute:(BOOL)mute {
    [self.rtcRoomApi muteCamera:mute];
}


- (void)onShowEngineStates:(id)sender {
    [self.rtcRoomApi setEngineStateStatistics:YES];
}

- (void)videoCallViewDidChangeRoute:(RTCVideoCallView *)view {
    _isSwitchSpeaker = !_isSwitchSpeaker;
    [self.rtcRoomApi switchLoundSpeaker];
}

- (void)videoCallViewDidEnableStats:(RTCVideoCallView *)view {
    BOOL isOpenStates = !self.bShowStates;
    [self.rtcRoomApi setEngineStateStatistics:isOpenStates];
    self.bShowStates = isOpenStates;

}

- (void)videoCallViewDidTapScreen:(CGPoint)point andPlaneSize:(CGSize)size {
    [self.rtcRoomApi cameraFocusWithPoint:point andPlaneSize:size];
}

- (void)hangup {
    [self.rtcRoomApi stopPublishStreaming:true];
    [self.rtcRoomApi logoutRtcRoom];
    //self.rtcRoomApi = nil;
    [_delegate viewControllerDidFinish:self];
}


- (NSString *)statusTextForState:(NSInteger)state {
    switch (state) {
        case RTC_CONNECTION_STATE_CONNECTING:
            return @"Connecting...";
        case RTC_CONNECTION_STATE_CONNECTED:
            break;
        case RTC_CONNECTION_STATE_DISCONNECTED:
            return @"Failed...";
        default:
            break;
    }
    return nil;
}

- (RTCVideoUserInfoView *)localUserInfoView {
    if (!_localUserInfoView) {
        _localUserInfoView = [[RTCVideoUserInfoView alloc] initWithFrame:CGRectMake(5, 0, 200, 40)];
    }
    return _localUserInfoView;
}

@end
