//
//  TMGRealTimeViewController.m
//  TMGDemoAudio
//
//  Created by RoonieChen on 2021/5/14.
//  Copyright © 2021 tobinchen. All rights reserved.
//

#import "TMGRealTimeViewController.h"
#import <Accelerate/Accelerate.h>
#import <CoreMotion/CoreMotion.h>


#import "APPIDKeys.h"
#import "GMESDK/TMGEngine.h"
#import "GMESDK/QAVAuthBuffer.h"
#import "DispatchCenter.h"


@interface TMGRealTimeViewController ()<ITMGDelegate>

@property (nonatomic, strong) UIScrollView *backScrollView;

@property (nonatomic, strong) UILabel *roomIDLabel;

@property (nonatomic, strong) UITextField *roomIdTF;

@property (nonatomic, strong) UILabel *roomTypeLabel;

@property (nonatomic, strong) UISegmentedControl *roomTypeControl;

@property (nonatomic, strong) UIButton *enterRoomBtn;

@property (nonatomic, strong) UIButton *exitRoomBtn;

@property (nonatomic, strong) UILabel *statusLabel;

@property (nonatomic, strong) UILabel *enableMicLabel;

@property (nonatomic, strong) UISwitch *enableMicSwitch;

@property (nonatomic, strong) UILabel *enableSpeakerLabel;

@property (nonatomic, strong) UISwitch *enableSpeakerSwitch;

@property (nonatomic, strong) UITextView *logTextView;


@property (nonatomic, assign) BOOL processEnd;

@end

@implementation TMGRealTimeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self configSDK];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)configSDK {
    self.roomIdTF.text = @"2018060";
    [[DispatchCenter getInstance] addDelegate:self];
}

- (void)setupUI {
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.backScrollView];
    [self.backScrollView addSubview:self.roomIDLabel];
    [self.backScrollView addSubview:self.roomIdTF];
    [self.backScrollView addSubview:self.roomTypeLabel];
    [self.backScrollView addSubview:self.roomTypeControl];
    [self.backScrollView addSubview:self.enterRoomBtn];
    [self.backScrollView addSubview:self.exitRoomBtn];
    [self.backScrollView addSubview:self.statusLabel];
    [self.backScrollView addSubview:self.enableMicLabel];
    [self.backScrollView addSubview:self.enableMicSwitch];
    [self.backScrollView addSubview:self.enableSpeakerLabel];
    [self.backScrollView addSubview:self.enableSpeakerSwitch];
    [self.backScrollView addSubview:self.logTextView];
    
    [self updateStatusEnterRoom:NO];

    [self layout];
}

- (void)updateStatusEnterRoom:(BOOL)enterRoom {
    self.enableMicSwitch.hidden = self.enableMicLabel.hidden = !enterRoom;
    self.enableSpeakerSwitch.hidden = self.enableSpeakerLabel.hidden = !enterRoom;
    if (!enterRoom) {
        self.enableMicSwitch.on = self.enableSpeakerSwitch.on = NO;
        self.logTextView.hidden = NO;
        self.statusLabel.hidden = YES;
    }
}

- (BOOL)isIPhoneNotchScreen {
    BOOL result = NO;
    if (UIDevice.currentDevice.userInterfaceIdiom != UIUserInterfaceIdiomPhone) {
        return result;
    }
    if (@available(iOS 11.0, *)) {
        UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window];
        if (mainWindow.safeAreaInsets.bottom > 0.0) {
            result = YES;
        }
    }
    return result;
}

- (CGFloat)safeTop {
    if ([self isIPhoneNotchScreen]) {
        return 88;
    }
    return 64;
}

- (void)layout {
    CGFloat left = 50;
    self.backScrollView.frame = CGRectMake(0, [self safeTop], self.view.frame.size.width, self.view.frame.size.height);
    //---------
    self.roomIDLabel.frame = CGRectMake(left, 30, 80, 30);
    self.roomIdTF.frame = CGRectMake(CGRectGetMaxX(self.roomIDLabel.frame) + 10, self.roomIDLabel.frame.origin.y, 130, 30);
    //---------
    self.roomTypeLabel.frame = CGRectMake(left, CGRectGetMaxY(self.roomIdTF.frame) + 10, 80, 30);
    self.roomTypeControl.frame = CGRectMake(CGRectGetMaxX(self.roomTypeLabel.frame) + 10, self.roomTypeLabel.frame.origin.y, 150, 30);
    //---------
    self.enterRoomBtn.frame = CGRectMake(left - 13, CGRectGetMaxY(self.roomTypeLabel.frame) + 10, 100, 30);
    self.exitRoomBtn.frame = CGRectMake(CGRectGetMaxX(self.enterRoomBtn.frame) + 30, self.enterRoomBtn.frame.origin.y, 100, 30);
    
    //---------
    self.enableMicLabel.frame = CGRectMake(left - 15, CGRectGetMaxY(self.exitRoomBtn.frame) + 10, 90, 30);
    self.enableMicSwitch.frame = CGRectMake(CGRectGetMaxX(self.enableMicLabel.frame), self.enableMicLabel.frame.origin.y, 50, 30);
    
    self.enableSpeakerLabel.frame = CGRectMake(CGRectGetMaxX(self.enableMicSwitch.frame) + 5, self.enableMicLabel.frame.origin.y, 90, 30);
    self.enableSpeakerSwitch.frame = CGRectMake(CGRectGetMaxX(self.enableSpeakerLabel.frame), self.enableSpeakerLabel.frame.origin.y, 50, 30);
    //---------
    self.statusLabel.frame = CGRectMake(left, CGRectGetMaxY(self.enableSpeakerSwitch.frame) + 5, self.backScrollView.frame.size.width - 2 * left, 30);
    //---------
    CGFloat ll = 30;
    CGRect commonRect = CGRectMake(ll, CGRectGetMaxY(self.statusLabel.frame) + 10, (self.backScrollView.frame.size.width - ll * 2), 400);
    self.logTextView.frame = commonRect;

    self.backScrollView.contentSize = CGSizeMake(self.backScrollView.frame.size.width, CGRectGetMaxY(commonRect) + self.backScrollView.frame.origin.y + 10);
}

#pragma mark - Action
- (void)roomTypeControlChanged:(UISegmentedControl *)segment {
    [[[ITMGContext GetInstance] GetRoom] ChangeRoomType:(int)segment.selectedSegmentIndex + 1];
}

- (void)enterRoomClick {
    NSData* authBuffer = [QAVAuthBuffer GenAuthBuffer:(unsigned int)self.appId.intValue roomID:self.roomIdTF.text openID:self.openId key:self.authKey];
    
    
    // Step 5/11 enter room, then you need handle ITMG_MAIN_EVENT_TYPE_ENTER_ROOM, ITMG_MAIN_EVENT_TYPE_USER_VOLUMES
    // and ITMG_MAIN_EVENT_TYPE_ROOM_DISCONNECT event
    // https://cloud.tencent.com/document/product/607/15221#.E5.8A.A0.E5.85.A5.E6.88.BF.E9.97.B4
    [[ITMGContext GetInstance] EnterRoom:self.roomIdTF.text roomType:(int)self.roomTypeControl.selectedSegmentIndex + 1 authBuffer:authBuffer];
}

- (void)dealloc {
    NSLog(@"TMGRealTimeViewController dealloc");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)exitRoomClick {
    // Step 10/11 exit room
    // 这里需要处理 ITMG_MAIN_EVENT_TYPE_EXIT_ROOM 事件
    // https://cloud.tencent.com/document/product/607/15221#.E9.80.80.E5.87.BA.E6.88.BF.E9.97.B4
    int nRet = [[ITMGContext GetInstance] ExitRoom];
    NSLog(@"nRet=%d", nRet);
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [[ITMGContext GetInstance] ExitRoom];
    [[DispatchCenter getInstance] removeDelegate:self];

}

- (void)backTap:(UITapGestureRecognizer *)tapGes {
    [self.view.window endEditing:YES];
}


- (void)micSwitch:(UISwitch *)micSwitch {
    // Step 8/11 enable to capture audio and send to server
    //https://cloud.tencent.com/document/product/607/15221#.E5.BC.80.E5.90.AF.E6.88.96.E5.85.B3.E9.97.AD.E9.BA.A6.E5.85.8B.E9.A3.8E
    [[[ITMGContext GetInstance] GetAudioCtrl] EnableMic:micSwitch.on];
}

- (void)speakerSwitch:(UISwitch *)speakerSwitch {
    // Step 9/11 enable to capture audio and send to server
    //https://cloud.tencent.com/document/product/607/15221#.E5.BC.80.E5.90.AF.E6.88.96.E5.85.B3.E9.97.AD.E6.89.AC.E5.A3.B0.E5.99.A8
    [[[ITMGContext GetInstance] GetAudioCtrl] EnableSpeaker:speakerSwitch.on];
}

#pragma mark - Lazy Loading

- (UIScrollView *)backScrollView {
    if (!_backScrollView) {
        _backScrollView = [[UIScrollView alloc]init];
        _backScrollView.backgroundColor = [UIColor whiteColor];
        UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backTap:)];
        [_backScrollView addGestureRecognizer:tapGes];
    }
    return _backScrollView;
}

- (UILabel *)roomIDLabel {
    if (!_roomIDLabel) {
        _roomIDLabel = [[UILabel alloc]init];
        _roomIDLabel.text = @"RoomID";
        _roomIDLabel.font = [UIFont systemFontOfSize:12];
    }
    return _roomIDLabel;
}

- (UITextField *)roomIdTF {
    if (!_roomIdTF) {
        _roomIdTF = [[UITextField alloc]init];
        _roomIdTF.borderStyle = UITextBorderStyleRoundedRect;
    }
    return _roomIdTF;
}

- (UILabel *)roomTypeLabel {
    if (!_roomTypeLabel) {
        _roomTypeLabel = [[UILabel alloc]init];
        _roomTypeLabel.text = @"RoomType:";
        _roomTypeLabel.font = [UIFont systemFontOfSize:12];
    }
    return _roomTypeLabel;
}

- (UISegmentedControl *)roomTypeControl {
    if (!_roomTypeControl) {
        _roomTypeControl = [[UISegmentedControl alloc]initWithItems:@[@"type1", @"type2", @"type3"]];
        [_roomTypeControl addTarget:self action:@selector(roomTypeControlChanged:) forControlEvents:UIControlEventValueChanged];
        _roomTypeControl.selectedSegmentIndex = 0;
    }
    return _roomTypeControl;
}

- (UIButton *)enterRoomBtn {
    if (!_enterRoomBtn) {
        _enterRoomBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_enterRoomBtn setTitle:@"EnterRoom" forState:UIControlStateNormal];
        [_enterRoomBtn addTarget:self action:@selector(enterRoomClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _enterRoomBtn;
}

- (UIButton *)exitRoomBtn {
    if (!_exitRoomBtn) {
        _exitRoomBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_exitRoomBtn setTitle:@"ExitRoom" forState:UIControlStateNormal];
        [_exitRoomBtn addTarget:self action:@selector(exitRoomClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _exitRoomBtn;
}

- (UILabel *)statusLabel
{
    if (!_statusLabel) {
        _statusLabel = [[UILabel alloc]init];
        _statusLabel.text = @"";
        _statusLabel.textAlignment = NSTextAlignmentCenter;
        _statusLabel.font = [UIFont systemFontOfSize:12];
    }
    return _statusLabel;
}


- (UILabel *)enableMicLabel {
    if (!_enableMicLabel) {
        _enableMicLabel = [[UILabel alloc]init];
        _enableMicLabel.text = @"Mic";
        _enableMicLabel.font = [UIFont systemFontOfSize:12];
    }
    return _enableMicLabel;
}

- (UISwitch *)enableMicSwitch {
    if (!_enableMicSwitch) {
        _enableMicSwitch = [[UISwitch alloc]init];
        [_enableMicSwitch addTarget:self action:@selector(micSwitch:) forControlEvents:UIControlEventValueChanged];
    }
    return _enableMicSwitch;
}

- (UILabel *)enableSpeakerLabel {
    if (!_enableSpeakerLabel) {
        _enableSpeakerLabel = [[UILabel alloc]init];
        _enableSpeakerLabel.text = @"Speaker";
        _enableSpeakerLabel.font = [UIFont systemFontOfSize:12];
    }
    return _enableSpeakerLabel;
}

- (UISwitch *)enableSpeakerSwitch {
    if (!_enableSpeakerSwitch) {
        _enableSpeakerSwitch = [[UISwitch alloc]init];
        [_enableSpeakerSwitch addTarget:self action:@selector(speakerSwitch:) forControlEvents:UIControlEventValueChanged];

    }
    return _enableSpeakerSwitch;
}

- (UITextView *)logTextView {
    if (!_logTextView) {
        _logTextView = [[UITextView alloc]init];
        _logTextView.font = [UIFont systemFontOfSize:10];
        _logTextView.layer.borderColor = [UIColor lightGrayColor].CGColor;
        _logTextView.layer.borderWidth = 0.5;
        _logTextView.editable = NO;
    }
    return _logTextView;
}


- (void)showLog:(NSString *)log {
    static int i = 0;
    NSString *text = self.logTextView.text;
    if (i < 3) {
        log = [text stringByAppendingFormat:@"\n%@", log];
        i++;
    } else {
        log = log;
        i = 0;
    }
    self.logTextView.text = log;
}

- (void)OnEvent:(ITMG_MAIN_EVENT_TYPE)eventType data:(NSDictionary *)data {
    if (ITMG_MAIN_EVENT_TYPE_USER_VOLUMES != eventType) {
        NSString *log = [NSString stringWithFormat:@"OnEvent:%d,data:%@", (int)eventType, data];
        [self showLog:log];
        NSLog(@"====%@====", log);
    }
    
    switch (eventType) {
        // Step 6/11 : Perform the enter room event
        case ITMG_MAIN_EVENT_TYPE_ENTER_ROOM: {
            int result = ((NSNumber *)[data objectForKey:@"result"]).intValue;
            NSString *error_info = [data objectForKey:@"error_info"];

            [self showLog:[NSString stringWithFormat:@"OnEnterRoomComplete:%d msg:(%@)", result, error_info]];

            if (result == 0) {
                [self updateStatusEnterRoom:YES];
            }
        }
        break;
        case ITMG_MAIN_EVENT_TYPE_EXIT_ROOM:
            // Step 11/11 : Perform the exit room event
        case ITMG_MAIN_EVENT_TYPE_ROOM_DISCONNECT: {
            [self showLog:[NSString stringWithFormat:@"EXIT_ROOM"]];
            [self updateStatusEnterRoom:NO];
        }
        break;
        case ITMG_MAIN_EVENT_TYPE_USER_VOLUMES: {
            //            // Step 7/11 : User in the room has new state, such as turn on/off microphone
            //            //            or new one enter/quit the room.
            //            //            more info please read the document.
            //            NSLog(@"ITMG_MAIN_EVENT_TYPE_USER_VOLUMES:%@ ", data);
            //            NSString *msg = [NSString stringWithFormat:@"vol:%@", data];
            //            msg = [msg stringByReplacingOccurrencesOfString:@"\n" withString:@""];
            //            [self showLog:msg];
            //        }
            //        break;
            
        case ITMG_MAIN_EVENT_TYPE_CHANGE_ROOM_QUALITY: {
            NSLog(@"ITMG_MAIN_EVENT_TYPE_CHANGE_ROOM_QUALITY:%@ ", data);
            int nWeight = ((NSNumber *)[data objectForKey:@"weight"]).intValue;
            float fLoss = ((NSNumber *)[data objectForKey:@"loss"]).floatValue;
            int nDelay = ((NSNumber *)[data objectForKey:@"delay"]).intValue;
            NSString *msg = [NSString stringWithFormat:@"Weight=%d, Loss=%f, Delay=%d", nWeight, fLoss, nDelay];
            [self showLog:msg];
            break;
        }
            break;
        default:
            break;
        }
    }
}


#pragma endregion

@end
