//
//  RTCVideoCallView.m
//  rtc_sdk_ios
//
//  Created by Sun,Jian(ACU-T102) on 2018/12/31.
//  Copyright © 2018年 Sun,Jian(ACU-T102). All rights reserved.
//

#import "RTCVideoCallView.h"
#import <AVFoundation/AVFoundation.h>
#import "BDCloudRTCBaseDefine.pch"
#import "UserRemoteManager.h"
#import "RTCSiglePageCallView.h"
#import "BDCloudRTCBaseDefine.pch"

#define angle2Rad(angle) ((angle) / 180.0 * M_PI)

static CGFloat const kButtonPadding = 82;
#define pageControlHeight 70

@implementation RtcViewLayoutInfo
@end

@implementation RTCRemoteVideoViewInfo
@end

@interface RTCVideoUserInfoView ()
@property (nonatomic, strong) UILabel *nameLabel;

@end

@implementation RTCVideoUserInfoView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setupViews];
    }
    return self;
}

- (void)setupViews {
    self.nameLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    self.nameLabel.font = [UIFont systemFontOfSize:14];
    self.nameLabel.textColor = [UIColor whiteColor];
    [self addSubview:self.nameLabel];
}

- (void)layoutSubviews {
    self.nameLabel.frame = CGRectMake(0, 0, self.bounds.size.width, 30);
}

- (void)setupUserId:(NSInteger)userId {
    
    self.nameLabel.text = [NSString stringWithFormat:@"%ld", userId];
    [self setNeedsLayout];
}

@end

@interface RTCVideoCallView () <RTCRemoteVideoViewDelegate>

@property (nonatomic, assign) BOOL isMuteMic;
@property (nonatomic, assign) BOOL isLoundSpeaker;
@property (nonatomic, assign) BOOL isSwitchVoice;
@property (nonatomic, assign) BOOL isSwitchCamear;
@property (nonatomic, assign) BOOL isOpeningMonitor;

@property(nonatomic, assign) BOOL isWatch;
@property(nonatomic, copy) NSString *sdkVersion;
@property (nonatomic, assign)  NSInteger userId;
@property (nonatomic, assign) CGFloat localVideoViewW;
@property (nonatomic, assign) CGFloat localVideoViewH;

@property (nonatomic, strong) RTCSiglePageCallView *siglePageCallView;
@end

@implementation RTCVideoCallView {
    UILabel* _muteCameraLabel;
    UIButton *_muteCamera;
    UILabel* _muteMicPhoneLabel;
    UIButton *_muteMicPhone;
    UILabel* _routChangeLabel;
    UIButton *_routeChangeButton;
    UILabel* _cameraSwitchLabel;
    UIButton *_cameraSwitchButton;
    UILabel* _hangupLabel;
    UIButton *_hangupButton;
    //display time label
    UILabel* _timeDisplayLabel;

    //display defaulty person photo
    UIImageView *_personPhotoImgView;
    
}
@synthesize roomInfoLabel = _roomInfoLabel;
@synthesize statusLabel = _statusLabel;
@synthesize delegate = _delegate;

- (instancetype)initWithFrame:(CGRect)frame
                      isWatch:(BOOL)isWatch
                          uid:(NSInteger)uid
                   sdkVersion:(NSString*)sdkVersion {
    if (self = [super initWithFrame:frame]) {
        self.isOpeningMonitor = YES;
        self.isWatch = isWatch;
        self.userId = uid;
        self.sdkVersion = sdkVersion;
        self.localVideoViewW = SCREEN_WIDTH*450*kLayoutWidthScale;
        self.localVideoViewH = SCREEN_HEIGHT*800*kLayoutHeightScale;
        

        self.localVideoView = [[RTCLocalVideoView alloc] initWithDelegate:nil];
//        [self updateSubViewLocal:_localVideoView];

        CGSize LocalView = CGSizeMake(720, 1280);
        
        self.siglePageCallView = [[RTCSiglePageCallView alloc] initWithFrame:CGRectZero isWatch:isWatch];
        [self.siglePageCallView addRTCsubView:[NSString stringWithFormat:@"%@", @(uid)]
                                        local:YES
                                         view:self.localVideoView.videoView
                                         size:LocalView
                                         show:YES];
        
        [self addSubview:self.siglePageCallView];

        _muteMicPhone = [UIButton buttonWithType:UIButtonTypeCustom];
        _muteMicPhone.layer.masksToBounds = YES;
        UIImage *micImage = [UIImage imageNamed:@"mute_mic_two_n.png"];
        [_muteMicPhone setImage:micImage forState:UIControlStateNormal];
        [_muteMicPhone addTarget:self action:@selector(onMicphoneChange:)
                forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_muteMicPhone];
        _muteMicPhoneLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _muteMicPhoneLabel.adjustsFontSizeToFitWidth = YES;
        _muteMicPhoneLabel.textColor = [UIColor whiteColor];
        _muteMicPhoneLabel.text = @"静音";
        [self addSubview:_muteMicPhoneLabel];

        _routeChangeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_routeChangeButton setImage:[UIImage imageNamed:@"loundspeaker_n.png"] forState:UIControlStateNormal];
        [_routeChangeButton setImage:[UIImage imageNamed:@"loundspeaker_y.png"] forState:UIControlStateSelected];
        [_routeChangeButton addTarget:self
                               action:@selector(onRouteChange:)
                     forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_routeChangeButton];
        _routChangeLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _routChangeLabel.adjustsFontSizeToFitWidth = YES;
        _routChangeLabel.textColor = [UIColor whiteColor];
        _routChangeLabel.text = @"扬声器";
        [self addSubview:_routChangeLabel];

        _hangupButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _hangupButton.layer.masksToBounds = YES;
        UIImage *image = [UIImage imageNamed:@"cancel_call.png"];
        [_hangupButton setImage:image forState:UIControlStateNormal];
        [_hangupButton addTarget:self
                          action:@selector(onHangup:)
                forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_hangupButton];
        _hangupLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _hangupLabel.adjustsFontSizeToFitWidth = YES;
        _hangupLabel.textColor = [UIColor whiteColor];
        _hangupLabel.text = @"取消";
        [self addSubview:_hangupLabel];

        _muteCamera = [UIButton buttonWithType:UIButtonTypeCustom];
        _muteCamera.layer.masksToBounds = YES;
        UIImage *cameraImage = [UIImage imageNamed:@"switch_voice_n.png"];
        [_muteCamera setImage:cameraImage forState:UIControlStateNormal];
        [_muteCamera addTarget:self action:@selector(onCameraChange:)
              forControlEvents:UIControlEventTouchUpInside];
        _muteCameraLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _muteCameraLabel.adjustsFontSizeToFitWidth = YES;
        _muteCameraLabel.textColor = [UIColor whiteColor];
        _muteCameraLabel.text = @"切到音频通话";
        [self addSubview:_muteCamera];
        [self addSubview:_muteCameraLabel];

        // TODO(tkchin): don't display this if we can't actually do camera switch.
        _cameraSwitchButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _cameraSwitchButton.layer.masksToBounds = YES;
        image = [UIImage imageNamed:@"switch_camera_n.png"];
        [_cameraSwitchButton setImage:image forState:UIControlStateNormal];
        [_cameraSwitchButton addTarget:self
                                action:@selector(onCameraSwitch:)
                      forControlEvents:UIControlEventTouchUpInside];
        
        _cameraSwitchLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _cameraSwitchLabel.adjustsFontSizeToFitWidth = YES;
        _cameraSwitchLabel.textColor = [UIColor whiteColor];
        _cameraSwitchLabel.text = @"切换摄像头";
        [self addSubview:_cameraSwitchButton];
        [self addSubview:_cameraSwitchLabel];

        _statusLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _statusLabel.font = [UIFont fontWithName:@"Roboto" size:16];
        _statusLabel.textColor = [UIColor whiteColor];
        [self addSubview:_statusLabel];

        _timeDisplayLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _timeDisplayLabel.adjustsFontSizeToFitWidth = YES;
        _timeDisplayLabel.textColor = [UIColor whiteColor];
        [self addSubview:_timeDisplayLabel];

        _personPhotoImgView = [[UIImageView alloc] init];
        UIImage *img = [UIImage imageNamed:@"first_page_logo.png"];
        [_personPhotoImgView setImage:img];
        [self addSubview:_personPhotoImgView];
        
        _roomInfoLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _roomInfoLabel.adjustsFontSizeToFitWidth = YES;
        _roomInfoLabel.textColor = [UIColor whiteColor];
        _roomInfoLabel.text = @"房间号：";
        [self addSubview:_roomInfoLabel];

        [self sendSubviewToBack:_personPhotoImgView];
        self.backgroundColor = [UIColor blackColor];

    }
    [UserRemoteManager instance].videoViewDelegate = self;
    return self;
}

#pragma mark - Video shown

- (CGRect)frameAtPosition:(int)postion {
    CGFloat maginH = SCREEN_WIDTH*350*kLayoutWidthScale;
    CGFloat width = SCREEN_WIDTH*414*kLayoutWidthScale;
    CGFloat height = SCREEN_WIDTH*414*kLayoutWidthScale;
    CGFloat x = (postion%3) * width;
    CGFloat y = (postion/3) * height;
    CGRect frame = CGRectMake(x, y+maginH, width, height);
    return frame;
}

- (void)layoutSubviews {
    CGRect bounds = self.bounds;
    CGRect localVideoFrame = CGRectMake(0, 0, self.localVideoViewW, self.localVideoViewH);

    CGFloat localVideoViewFrameX = SCREEN_WIDTH*29*kLayoutWidthScale;
    CGFloat localVideoViewFrameY = SCREEN_HEIGHT*210*kLayoutHeightScale;
    CGFloat localVideoViewFrameW = SCREEN_WIDTH*450*kLayoutWidthScale;
    CGFloat localVideoViewFrameH = SCREEN_HEIGHT*600*kLayoutHeightScale;
    if (self.isWatch) {
        localVideoViewFrameH = localVideoViewFrameW;
    }
    localVideoFrame = CGRectMake(localVideoViewFrameX, localVideoViewFrameY, localVideoViewFrameW, localVideoViewFrameH);

    CGFloat viewScrollViewX = SCREEN_WIDTH*0*kLayoutWidthScale;
    CGFloat viewScrollViewY = SCREEN_HEIGHT*300*kLayoutHeightScale;
    CGFloat viewScrollViewW = SCREEN_WIDTH*1242*kLayoutWidthScale;
    CGFloat viewScrollViewH = SCREEN_HEIGHT*1430*kLayoutHeightScale;

    self.siglePageCallView.frame = CGRectMake(viewScrollViewX, viewScrollViewY, viewScrollViewW, viewScrollViewH);
    
    // Aspect fit local video view into a square box.
    self.localVideoView.videoView.frame = localVideoFrame;
    
    CGFloat stateViewYoffset = SCREEN_HEIGHT*267*kLayoutHeightScale;
    stateViewYoffset = SCREEN_HEIGHT*800*kLayoutHeightScale;

    //mute micphone btn and label
    CGFloat muteMicX = 0;
    CGFloat muteMicY = 0;
    CGFloat muteMicW = SCREEN_WIDTH*160*kLayoutWidthScale;
    CGFloat muteMicH = muteMicW;

    muteMicX = SCREEN_WIDTH*88*kLayoutWidthScale;
    muteMicY = SCREEN_HEIGHT*1883*kLayoutHeightScale;

    _muteMicPhone.layer.cornerRadius = muteMicW/2.0;
    CGRect micPhoneFrame = CGRectMake(muteMicX, muteMicY, muteMicW, muteMicH);
    _muteMicPhone.frame = micPhoneFrame;
    CGFloat muteMicLabelX = 0;
    CGFloat muteMicLabelY = 0;

    muteMicLabelX = SCREEN_WIDTH*140*kLayoutWidthScale;
    muteMicLabelY = muteMicY + muteMicH - SCREEN_HEIGHT*23*kLayoutHeightScale;

    CGFloat muteMicLabelW = SCREEN_WIDTH*60*kLayoutWidthScale;
    CGFloat muteMicLabelH = muteMicW*42/60;
    _muteMicPhoneLabel.frame = CGRectMake(muteMicLabelX,
                                          muteMicLabelY,
                                          muteMicLabelW,
                                          muteMicLabelH);

    CGRect routeChangeFrame = _muteMicPhone.frame;
    routeChangeFrame.origin.x = CGRectGetMaxX(routeChangeFrame)
                                + SCREEN_WIDTH*kButtonPadding*kLayoutWidthScale;

    _routeChangeButton.layer.cornerRadius = muteMicW/2.0;
    _routeChangeButton.frame = routeChangeFrame;
    CGFloat routeChangeLabelX = SCREEN_WIDTH*368*kLayoutWidthScale;
    CGFloat routeChangeLabelY = muteMicLabelY;
    CGFloat routeChangeLabelW = SCREEN_WIDTH*90*kLayoutWidthScale;
    CGFloat routeChangeLabelH = muteMicLabelH;

    _routChangeLabel.frame = CGRectMake(routeChangeLabelX,
                                        routeChangeLabelY,
                                        routeChangeLabelW,
                                        routeChangeLabelH);

    CGFloat hangupBtnX = CGRectGetMaxX(routeChangeFrame) + SCREEN_WIDTH*83*kLayoutWidthScale;
    CGFloat hangupBtnY = SCREEN_HEIGHT*1886*kLayoutHeightScale;
    CGFloat hangupBtnW = SCREEN_WIDTH*155*kLayoutWidthScale;
    CGFloat hangupBtnH = hangupBtnW;

    _hangupButton.layer.cornerRadius = hangupBtnW/2.0;
    _hangupButton.frame = CGRectMake(hangupBtnX, hangupBtnY, hangupBtnW, hangupBtnH);
    CGFloat hungupLabelX = SCREEN_WIDTH*623*kLayoutWidthScale;
    CGFloat hungupLabelY = muteMicLabelY;
    CGFloat hungupLabelW = SCREEN_WIDTH*60*kLayoutWidthScale;
    CGFloat hungupLabelH = muteMicLabelH;

    _hangupLabel.frame = CGRectMake(hungupLabelX,
                                    hungupLabelY,
                                    hungupLabelW,
                                    hungupLabelH);

    CGFloat muteCameraX = CGRectGetMaxX(_hangupButton.frame) + SCREEN_WIDTH*83*kLayoutWidthScale;
    CGFloat muteCameraY = muteMicY;
    CGFloat muteCameraW = muteMicW;
    CGFloat muteCameraH = muteMicH;
    CGRect muteCameraFrame = CGRectMake(muteCameraX, muteCameraY, muteCameraW, muteCameraH);
    _muteCamera.layer.cornerRadius = muteCameraW/2.0;
    _muteCamera.frame = muteCameraFrame;
    CGFloat muteCameraLabelX = SCREEN_WIDTH*806*kLayoutWidthScale;
    CGFloat muteCameraLabelY = muteMicLabelY;
    CGFloat muteCameraLabelW = SCREEN_WIDTH*180*kLayoutWidthScale;
    CGFloat muteCameraLabelH = muteMicLabelH;
    _muteCameraLabel.frame = CGRectMake(muteCameraLabelX,
                                        muteCameraLabelY,
                                        muteCameraLabelW,
                                        muteCameraLabelH);

    CGFloat switchCameraX = CGRectGetMaxX(_muteCamera.frame) + SCREEN_WIDTH*kButtonPadding*kLayoutWidthScale;
    CGFloat switchCameraY = muteMicY;
    CGFloat switchCameraW = muteMicW;
    CGFloat switchCameraH = muteMicH;
    CGRect cameraSwitchFrame = CGRectMake(switchCameraX, switchCameraY, switchCameraW, switchCameraH);
    _cameraSwitchButton.layer.cornerRadius = muteCameraW/2.0;
    _cameraSwitchButton.frame = cameraSwitchFrame;
    CGFloat switchCameraLabelX = SCREEN_WIDTH*1062*kLayoutWidthScale;
    CGFloat switchCameraLabelY = muteMicLabelY;
    CGFloat switchCameraLabelW = SCREEN_WIDTH*150*kLayoutWidthScale;
    CGFloat switchCameraLabelH = muteMicLabelH;
    _cameraSwitchLabel.frame = CGRectMake(switchCameraLabelX,
                                          switchCameraLabelY,
                                          switchCameraLabelW,
                                          switchCameraLabelH);
    [self layoutBaseContentSubView:bounds];
}

- (void)layoutBaseContentSubView:(CGRect)bounds {
    [_statusLabel sizeToFit];
    _statusLabel.center = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds));
    _roomInfoLabel.frame = CGRectMake(20, 40, 300, 20);
    // adding time display
    CGFloat timeDisplayLabelX = SCREEN_WIDTH*580*kLayoutWidthScale;
    CGFloat timeDisplayLabelY = SCREEN_HEIGHT*1728*kLayoutHeightScale;
    CGFloat timeDisplayLabelW = SCREEN_WIDTH*100*kLayoutWidthScale;
    CGFloat timeDisplayLabelH = timeDisplayLabelW*56/100;
    _timeDisplayLabel.frame = CGRectMake(timeDisplayLabelX,
                                         timeDisplayLabelY,
                                         timeDisplayLabelW,
                                         timeDisplayLabelH);
    _timeDisplayLabel.text = [self getCurrentTime];
}

#pragma mark - RTCEAGLVideoViewDelegate
- (void)remoteVideoView:(RTCRemoteVideoView *)videoView didChangeVideoSize:(CGSize)size {
    //TODO changeVideoSize info
    NSLog(@"didChangeVideoSize : size width:%f, height:%f", size.width, size.height);
    
}

#pragma mark - Private
- (void)onMicphoneChange:(id)sender {
    if (!self.isMuteMic) {
        self.isMuteMic = YES;
        UIImage *img = [UIImage imageNamed:@"mute_mic_two_y.png"];
        [_muteMicPhone setImage:img forState:UIControlStateNormal];
    } else {
        self.isMuteMic = NO;
        UIImage *img = [UIImage imageNamed:@"mute_mic_two_n.png"];
        [_muteMicPhone setImage:img forState:UIControlStateNormal];
    }
    [_delegate videoCallViewDidMuteMicphone:self];
}

- (void)onCameraSwitch:(id)sender {
    
    if (!self.isSwitchCamear) {
        self.isSwitchCamear = YES;
        UIImage* img = [UIImage imageNamed:@"switch_camera_y.png"];
        [_cameraSwitchButton setImage:img forState:UIControlStateNormal];
    } else {
        self.isSwitchCamear = NO;
        UIImage* img = [UIImage imageNamed:@"switch_camera_n.png"];
        [_cameraSwitchButton setImage:img forState:UIControlStateNormal];
    }
    [_delegate videoCallViewDidSwitchCamera:self];
}

- (void)onCameraChange:(id)sender {
    if (!self.isSwitchVoice) {
        self.isSwitchVoice = YES;
        UIImage* img = [UIImage imageNamed:@"switch_voice_y.png"];
        [_muteCamera setImage:img forState:UIControlStateNormal];
    } else {
        self.isSwitchVoice = NO;
        UIImage* img = [UIImage imageNamed:@"switch_voice_n.png"];
        [_muteCamera setImage:img forState:UIControlStateNormal];
    }
    [_delegate videoCallViewDidMuteCamera:self mute:!self.isSwitchVoice];
}

- (void)onRouteChange:(id)sender {
    [self updateRouteChangeStatus:!self.isLoundSpeaker];
    [_delegate videoCallViewDidChangeRoute:self];
}

- (void)updateRouteChangeStatus:(BOOL)isLoundSpeaker {
    if (isLoundSpeaker) {
        self.isLoundSpeaker = YES;
        _routeChangeButton.selected = YES;
    } else {
        self.isLoundSpeaker = NO;
        _routeChangeButton.selected = NO;
    }
}

- (void)onHangup:(id)sender {
    [_delegate videoCallViewDidHangup:self];
}

- (NSString*)getCurrentTime {
    NSDate *date = [NSDate date];
    NSDateFormatter *dft=[[NSDateFormatter alloc] init];
    [dft setDateFormat:@"hh:mm"];
    NSString *dateStr;
    dateStr = [dft stringFromDate:date];
    return dateStr;
}

#pragma  mark ViewGroups manager view shown in two mode

- (void)updateSubView:(RTCRemoteVideoView*)remoteView
                  uid:(NSInteger)userID
                  add:(BOOL)boAdd {
    remoteView.rtcVideoViewMode = RTCVideoViewScaleAspectFit;
    NSUInteger countViews = [[UserRemoteManager instance] remoteSubscribeNumers];
    
    if (boAdd) {
       [self.siglePageCallView addRTCsubView:[NSString stringWithFormat:@"%ld",(long)userID] local:NO view:remoteView.videoView size:remoteView.videoResolution show:(countViews < BDSiglePageNumber)?YES:NO];
    } else {
        [self.siglePageCallView removeRTCsubView:[NSString stringWithFormat:@"%ld",(long)userID]];
    }

    NSArray *remoteAllUsers = [[UserRemoteManager instance] remoteAllUsers];
    for (int i = 0; i < remoteAllUsers.count; i++) {
        RTCRemoteVideoViewInfo *userInfo = remoteAllUsers[i];
        NSString *userId = [NSString stringWithFormat:@"%ld", userInfo.userId];
        if ([self.siglePageCallView.remoteUids containsObject:userId]) {
            NSLog(@"vocs view appear for userId:%@", userId);
            [_delegate videoCallViewDidRemoteviewDisappear:NO remoteUid:userId];
        } else {
            if ([self.siglePageCallView.allAddedUids containsObject:userId]) {
                NSLog(@"vocs view disappear for userId:%@", userId);
                [_delegate videoCallViewDidRemoteviewDisappear:YES remoteUid:userId];
                [self.siglePageCallView.allAddedUids removeObject:userId];
            }
        }
    }
}

- (UIImage *)captureImageFromView:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions(view.frame.size,NO, 0);
    [[UIColor clearColor] setFill];
    [[UIBezierPath bezierPathWithRect:view.bounds] fill];
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:ctx];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

@end

