//
//  HWMConfCtrlViewController.m
//  HWMUISDKNativeDemo
//
//

#import "HWMConfCtrlViewController.h"
#import "HWMSDKTableView.h"
#import "HWMInputView.h"
#import <HWMUISDK/HWMUISDK.h>

typedef NS_ENUM (NSInteger, HWMConfCtrlCellType) {
    HWMConfCtrlCellTypeOpenSubtitle = 0, // 打开/关闭字幕
    HWMConfCtrlCellTypeSubtitlePageOpened, // 是否已经打开字幕
    HWMConfCtrlCellTypeOpenWaitingRoom, // 打开/关闭等候室
    HWMConfCtrlCellTypeWaitingRoomOpened, // 是否已经打开等候室
    HWMConfCtrlCellTypeOperateLocalRecord, // 操作本地录制
    HWMConfCtrlCellTypeLocalRecordStatus, // 获取本地录制状态
    HWMConfCtrlCellTypeSelfHasLocalRecordPermission, // 是否有本地录制权限
    HWMConfCtrlCellTypeRequestLocalRecordPermission, // 申请本地录制权限
    HWMConfCtrlCellTypeApplyHostRole, // 申请主持人
    HWMConfCtrlCellTypeOpenVirtualBackgroundSettingPage, // 打开虚拟背景设置
    HWMConfCtrlCellTypeVirtualBackgroundSettingPageOpened, // 是否已经打开虚拟背景设置
    HWMConfCtrlCellTypeSubscribeSubtitle, // 订阅/取消订阅字幕
    HWMConfCtrlCellTypeSubscribeSubtitleLanguage, // 订阅字幕语言
    HWMConfCtrlCellTypeGetSubtitleSupportLanguage, // 获取字幕支持的语言
    HWMConfCtrlCellTypeRealTimeSubtitleInfoNotify, // 字幕消息实时通知
    HWMConfCtrlCellTypeConfIsSupportSubtitle, // 是否支持字幕
};

typedef NS_ENUM (NSInteger, HWMConfCtrlCellViewType) {
    HWMConfCtrlCellViewTypeNormal = 0,
    HWMConfCtrlCellViewTypePopUp,
    HWMConfCtrlCellViewTypeInput,
    HWMConfCtrlCellViewTypeNotify,
};

@interface HWMConfCtrlTableViewCell : NSTableCellView

+ (instancetype)initConfCtrlTableViewCell:(NSTableView *)tableView ower:(nullable id)ower;

@property (nonatomic, strong) NSTextField *titleLabel;
@property (nonatomic, strong) NSTextField *notifyLabel;
@property (nonatomic, strong) NSView *contentView;
@property (nonatomic, strong) NSView *buttonsView;
@property (nonatomic, strong) NSArray<NSString *> *buttonArray;
@property (nonatomic, copy) void (^buttonEvent)(NSInteger index);
@property (nonatomic, strong) NSPopUpButton *popUpButton;
@property (nonatomic, strong) HWMInputView *inputView;
@property (nonatomic, assign) HWMConfCtrlCellViewType type;

@end

@implementation HWMConfCtrlTableViewCell

+ (instancetype)initConfCtrlTableViewCell:(NSTableView *)tableView ower:(nullable id)ower {
    HWMConfCtrlTableViewCell *cell = [tableView makeViewWithIdentifier:NSStringFromClass([HWMConfCtrlTableViewCell class]) owner:ower];
    if (!cell) {
        cell = [[HWMConfCtrlTableViewCell alloc] initWithFrame:NSMakeRect(0, 0, 300, 40)];
        cell.identifier = NSStringFromClass([HWMConfCtrlTableViewCell class]);
    }
    return cell;
}

- (instancetype)initWithFrame:(NSRect)frameRect {
    if (self = [super initWithFrame:frameRect]) {
        self.wantsLayer = YES;
        self.layer.backgroundColor = [NSColor whiteColor].CGColor;
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    self.titleLabel = [NSTextField hwm_fieldWithTitle:@"" titleColor:[NSColor colorWithRGB:0x666666] font:[NSFont systemFontOfSize:13]];
    [self addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.centerY.mas_equalTo(0);
        make.width.mas_equalTo(200);
    }];
    
    self.contentView = [[NSView alloc] init];
    [self addSubview:self.contentView];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.titleLabel.mas_trailing);
        make.centerY.mas_equalTo(0);
        make.width.mas_equalTo(150);
        make.height.mas_equalTo(40);
    }];
    
    self.buttonsView = [[NSView alloc] init];
    [self addSubview:self.buttonsView];
    [self.buttonsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.contentView.mas_trailing);
        make.trailing.centerY.mas_equalTo(0);
        make.height.mas_equalTo(40);
    }];
}

- (void)setType:(HWMConfCtrlCellViewType)type {
    _type = type;
    [self.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    CGFloat contentWidth = type == HWMConfCtrlCellViewTypeNotify ? 380 : 150;
    [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(contentWidth);
    }];
    switch (type) {
        case HWMConfCtrlCellViewTypePopUp: {
            [self.contentView addSubview:self.popUpButton];
            [self.popUpButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.mas_equalTo(0);
            }];
        }
            break;
        case HWMConfCtrlCellViewTypeInput: {
            [self.contentView addSubview:self.inputView];
            [self.inputView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.mas_equalTo(0);
            }];
        }
            break;
        case HWMConfCtrlCellViewTypeNotify: {
            [self.contentView addSubview:self.notifyLabel];
            [self.notifyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.leading.trailing.centerY.mas_equalTo(0);
            }];
        }
            break;
        default:
            break;
    }
}

- (void)setButtonArray:(NSArray<NSString *> *)buttonArray {
    _buttonArray = buttonArray;
    [self.buttonsView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [buttonArray enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSButton *button = [self createButton:obj tag:idx];
        [self.buttonsView addSubview:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.trailing.mas_equalTo(-90.0 * idx);
            make.centerY.mas_equalTo(0);
            make.size.mas_equalTo(NSMakeSize(80, 30));
        }];
    }];
}

- (NSButton *)createButton:(NSString *)title tag:(NSInteger)tag {
    NSButton *button = [NSButton buttonWithTitle:title font:nil fontColor:[NSColor whiteColor] target:self action:@selector(buttonEvent:)];
    button.layer.backgroundColor = [NSColor colorWithRGB:0x0D94FF].CGColor;
    button.layer.cornerRadius = 4.0;
    button.layer.masksToBounds = YES;
    button.tag = tag;
    return button;
}

- (HWMInputView *)inputView {
    if (!_inputView) {
        _inputView = [[HWMInputView alloc] init];
    }
    return _inputView;
}

- (NSPopUpButton *)popUpButton {
    if (!_popUpButton) {
        _popUpButton = [[NSPopUpButton alloc] init];
        _popUpButton.target = self;
        _popUpButton.action = @selector(popUpButtonEvent:);
    }
    return _popUpButton;
}

- (NSTextField *)notifyLabel {
    if (!_notifyLabel) {
        _notifyLabel = [NSTextField hwm_fieldWithTitle:@"" titleColor:[NSColor colorWithRGB:0x666666] font:[NSFont systemFontOfSize:13]];
    }
    return _notifyLabel;
}

#pragma mark - Event

- (void)buttonEvent:(NSButton *)button {
    if (self.buttonEvent) {
        self.buttonEvent(button.tag);
    }
}

- (void)popUpButtonEvent:(NSPopUpButton *)button {
    self.buttonArray = @[button.selectedItem.title];
}

@end

@interface HWMConfCtrlViewController () <HWMSDKTableViewDelegate, HWMSDKTableViewDataSourse, HWMBizNotificationHandler>

@property (nonatomic, copy) NSDictionary<NSNumber *, NSString *> *titleDic;
@property (nonatomic, copy) NSDictionary<NSNumber *, NSString *> *subtitleLanguageDic;
@property (nonatomic, strong) HWMSDKTableView *tableView;

@end

@implementation HWMConfCtrlViewController

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

- (void)viewWillAppear {
    [[HWMSdk getSdkConfig] subscribeBizNotificationHandler:self];
}

- (void)setupData {
    self.titleDic = @{
        @(HWMConfCtrlCellTypeOpenSubtitle) : @"打开/关闭字幕",
        @(HWMConfCtrlCellTypeSubtitlePageOpened) : @"是否已经打开字幕",
        @(HWMConfCtrlCellTypeOpenWaitingRoom) : @"打开/关闭等候室",
        @(HWMConfCtrlCellTypeWaitingRoomOpened) : @"是否已经打开等候室",
        @(HWMConfCtrlCellTypeOperateLocalRecord) : @"操作本地录制",
        @(HWMConfCtrlCellTypeLocalRecordStatus) : @"获取本地录制状态",
        @(HWMConfCtrlCellTypeSelfHasLocalRecordPermission) : @"是否有本地录制权限",
        @(HWMConfCtrlCellTypeRequestLocalRecordPermission) : @"申请本地录制权限",
        @(HWMConfCtrlCellTypeApplyHostRole) : @"申请主持人",
        @(HWMConfCtrlCellTypeOpenVirtualBackgroundSettingPage) : @"打开虚拟背景设置",
        @(HWMConfCtrlCellTypeVirtualBackgroundSettingPageOpened) : @"是否已经打开虚拟背景设置",
        @(HWMConfCtrlCellTypeSubscribeSubtitle) : @"订阅/取消订阅字幕",
        @(HWMConfCtrlCellTypeSubscribeSubtitleLanguage) : @"订阅字幕语言",
        @(HWMConfCtrlCellTypeGetSubtitleSupportLanguage) : @"获取字幕支持的语言",
        @(HWMConfCtrlCellTypeRealTimeSubtitleInfoNotify) : @"字幕消息实时通知",
        @(HWMConfCtrlCellTypeConfIsSupportSubtitle) : @"是否支持字幕",
    };
    self.subtitleLanguageDic = @{
        @(HWMUISDKSubtitleLanguageDefault) : @"默认不翻译",
        @(HWMUISDKSubtitleLanguageCn) : @"中文",
        @(HWMUISDKSubtitleLanguageEn) : @"英文",
        @(HWMUISDKSubtitleLanguageGe) : @"德文",
        @(HWMUISDKSubtitleLanguageFr) : @"法语",
        @(HWMUISDKSubtitleLanguageRu) : @"俄语",
        @(HWMUISDKSubtitleLanguageJa) : @"日语",
        @(HWMUISDKSubtitleLanguageKo) : @"韩语",
        @(HWMUISDKSubtitleLanguageEs) : @"西班牙语",
        @(HWMUISDKSubtitleLanguagePt) : @"葡萄牙语",
        @(HWMUISDKSubtitleLanguageAr) : @"阿拉伯语",
        @(HWMUISDKSubtitleLanguageIt) : @"意大利语",
        @(HWMUISDKSubtitleLanguageTh) : @"泰语 ",
        @(HWMUISDKSubtitleLanguageId) : @"印度尼西亚语",
        @(HWMUISDKSubtitleLanguageMs) : @"马来语",
        @(HWMUISDKSubtitleLanguageTr) : @"土耳其语",
    };
}

- (void)setupUI {
    self.tableView = [[HWMSDKTableView alloc] initTableViewClomuIdentifier:@"HWMConfCtrlTableView"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.top.mas_equalTo(15);
        make.trailing.bottom.mas_equalTo(-15);
    }];
}

#pragma mark - Delegate

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
    return self.titleDic.count;
}

- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    HWMConfCtrlTableViewCell *cell = [HWMConfCtrlTableViewCell initConfCtrlTableViewCell:tableView ower:self];
    cell.titleLabel.stringValue = self.titleDic[@(row)];
    cell.buttonArray = @[];
    cell.type = HWMConfCtrlCellViewTypeNormal;
    switch (row) {
        case HWMConfCtrlCellTypeOpenSubtitle: {
            cell.buttonArray = @[@"关闭", @"打开"];
            cell.buttonEvent = ^(NSInteger index) {
                BOOL isOpen = index == 1;
                [[HWMBizSdk getBizOpenApi] openSubtitle:isOpen callback:^(NSError * _Nullable error, id  _Nullable result) {
                    if (error) {
                        [HWMConsoleManager shareInstance].error = error;
                    } else {
                        [HWMConsoleManager shareInstance].console = @"open subtitle success";
                    }
                }];
            };
        }
            break;
        case HWMConfCtrlCellTypeSubtitlePageOpened: {
            cell.buttonArray = @[@"获取"];
            cell.buttonEvent = ^(NSInteger index) {
                BOOL isOpened = [[HWMBizSdk getBizOpenApi] subtitlePageOpened];
                [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"subtitle page opened: %d", isOpened];
            };
        }
            break;
        case HWMConfCtrlCellTypeOpenWaitingRoom: {
            cell.buttonArray = @[@"关闭", @"打开"];
            cell.buttonEvent = ^(NSInteger index) {
                BOOL isOpen = index == 1;
                [[HWMBizSdk getBizOpenApi] openWaitingRoom:isOpen callback:^(NSError * _Nullable error, id  _Nullable result) {
                    if (error) {
                        [HWMConsoleManager shareInstance].error = error;
                    } else {
                        [HWMConsoleManager shareInstance].console = @"open waiting room success";
                    }
                }];
            };
        }
            break;
        case HWMConfCtrlCellTypeWaitingRoomOpened: {
            cell.buttonArray = @[@"获取"];
            cell.buttonEvent = ^(NSInteger index) {
                BOOL isOpened = [[HWMBizSdk getBizOpenApi] waitingRoomOpened];
                [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"waiting room opened: %d", isOpened];
            };
        }
            break;
        case HWMConfCtrlCellTypeOperateLocalRecord: {
            cell.type = HWMConfCtrlCellViewTypePopUp;
            [cell.popUpButton addItemsWithTitles:@[@"开始录制", @"停止录制", @"暂停录制", @"恢复录制"]];
            cell.buttonArray = @[@"开始录制"];
            @weakify(cell);
            cell.buttonEvent = ^(NSInteger index) {
                @strongify(cell);
                HWMUISDKLocalRecordOperateType type = (HWMUISDKLocalRecordOperateType)cell.popUpButton.indexOfSelectedItem;
                [[HWMBizSdk getBizOpenApi] operateLocalRecordWithType:type callback:^(NSError * _Nullable error, id  _Nullable result) {
                    if (error) {
                        [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"operate local record error: %@", error];
                    } else {
                        [HWMConsoleManager shareInstance].console = @"operate local record success";
                    }
                }];
            };
        }
            break;
        case HWMConfCtrlCellTypeLocalRecordStatus: {
            cell.buttonArray = @[@"获取"];
            cell.buttonEvent = ^(NSInteger index) {
                HWMUISDKLocalRecordStatus status = [[HWMBizSdk getBizOpenApi] getConfLocalRecordStatus];
                [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"local record status: %ld", status];
            };
        }
            break;
        case HWMConfCtrlCellTypeSelfHasLocalRecordPermission: {
            cell.buttonArray = @[@"获取"];
            cell.buttonEvent = ^(NSInteger index) {
                BOOL hasPermission = [[HWMBizSdk getBizOpenApi] getSelfHasLocalRecordPermission];
                [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"self has local record permission: %d", hasPermission];
            };
        }
            break;
        case HWMConfCtrlCellTypeRequestLocalRecordPermission: {
            cell.buttonArray = @[@"申请"];
            cell.buttonEvent = ^(NSInteger index) {
                [[HWMBizSdk getBizOpenApi] requestLocalRecordPermissionWithCallback:^(NSError * _Nullable error, id  _Nullable result) {
                    if (error) {
                        [HWMConsoleManager shareInstance].error = error;
                    } else {
                        [HWMConsoleManager shareInstance].console = @"request local record permission success";
                    }
                }];
            };
        }
            break;
        case HWMConfCtrlCellTypeApplyHostRole: {
            cell.buttonArray = @[@"申请"];
            cell.type = HWMConfCtrlCellViewTypeInput;
            cell.inputView.placeholder = @"输入主持人密码";
            @weakify(cell);
            cell.buttonEvent = ^(NSInteger index) {
                @strongify(cell);
                [[HWMBizSdk getBizOpenApi] applyHostRoleWithPassword:cell.inputView.textField.stringValue callback:^(NSError * _Nullable error, id  _Nullable result) {
                    if (error) {
                        [HWMConsoleManager shareInstance].error = error;
                    } else {
                        [HWMConsoleManager shareInstance].console = @"apply host role success";
                    }
                }];
            };
        }
            break;
        case HWMConfCtrlCellTypeOpenVirtualBackgroundSettingPage: {
            cell.buttonArray = @[@"打开"];
            cell.buttonEvent = ^(NSInteger index) {
                [[HWMBizSdk getBizOpenApi] openVirtualBackgroundSettingPageWithCallback:^(NSError * _Nullable error, id  _Nullable result) {
                    if (error) {
                        [HWMConsoleManager shareInstance].error = error;
                    } else {
                        [HWMConsoleManager shareInstance].console = @"open virtual background setting page success";
                    }
                }];
            };
        }
            break;
        case HWMConfCtrlCellTypeVirtualBackgroundSettingPageOpened: {
            cell.buttonArray = @[@"获取"];
            cell.buttonEvent = ^(NSInteger index) {
                BOOL isOpened = [[HWMBizSdk getBizOpenApi] virtualBackgroundSettingPageOpened];
                [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"virtual background setting page opened: %d", isOpened];
            };
        }
            break;
        case HWMConfCtrlCellTypeSubscribeSubtitle: {
            cell.buttonArray = @[@"取消订阅", @"订阅"];
            cell.buttonEvent = ^(NSInteger index) {
                BOOL isSubscribe = index == 1;
                [[HWMBizSdk getBizOpenApi] subscribeSubtitle:isSubscribe callback:^(NSError * _Nullable error, id  _Nullable result) {
                    if (error) {
                        [HWMConsoleManager shareInstance].error = error;
                    } else {
                        [HWMConsoleManager shareInstance].console = @"subscribe subtitle success";
                    }
                }];
            };
        }
            break;
        case HWMConfCtrlCellTypeSubscribeSubtitleLanguage: {
            cell.buttonArray = @[@"订阅"];
            cell.type = HWMConfCtrlCellViewTypeInput;
            cell.inputView.placeholder = @"输入字幕语言type";
            @weakify(cell);
            cell.buttonEvent = ^(NSInteger index) {
                @strongify(cell);
                HWMUISDKTargetLanguageType type = [cell.inputView.textField.stringValue integerValue];
                [[HWMBizSdk getBizOpenApi] subscribeSubtitleLanguageWithType:type callback:^(NSError * _Nullable error, id  _Nullable result) {
                    if (error) {
                        [HWMConsoleManager shareInstance].error = error;
                    } else {
                        [HWMConsoleManager shareInstance].console = @"subscribe subtitle language success";
                    }
                }];
            };
        }
            break;
        case HWMConfCtrlCellTypeGetSubtitleSupportLanguage: {
            cell.buttonArray = @[@"获取"];
            cell.buttonEvent = ^(NSInteger index) {
                HWMUISDKTargetLanguageTypeListModel *model = [[HWMBizSdk getBizOpenApi] getSubtitleSupportLanguage];
                __block NSMutableString *string = [[NSMutableString alloc] initWithString:@"字幕支持的语言:\n"];
                [model.targetLanguageTypes enumerateObjectsUsingBlock:^(HWMUISDKTargetLanguageTypeInfoModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    [string appendFormat:@"%@ type: %ld\n", self.subtitleLanguageDic[@(obj.targetLanguageType)], obj.targetLanguageType];
                }];
                [HWMConsoleManager shareInstance].console = string;
            };
        }
            break;
        case HWMConfCtrlCellTypeRealTimeSubtitleInfoNotify: {
            cell.type = HWMConfCtrlCellViewTypeNotify;
        }
            break;
        case HWMConfCtrlCellTypeConfIsSupportSubtitle: {
            cell.buttonArray = @[@"获取"];
            cell.buttonEvent = ^(NSInteger index) {
                BOOL isSupportSubtitle = [[HWMBizSdk getBizOpenApi] getConfIsSupportSubtitle];
                [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"is support subtitle: %d", isSupportSubtitle];
            };
        }
            break;
        default:
            break;
    }
    return cell;
}

- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row {
    return 40;
}

#pragma mark - HWMBizNotificationHandler

/// 字幕消息实时通知
- (void)onRealTimeSubtitleInfoNotify:(HWMSDKRealTimeSubtitleModel *)realTimeSubtitle {
    NSMutableString *string = [[NSMutableString alloc] init];
    [string appendFormat:@"originalMsg: %@\n", realTimeSubtitle.originalMsg];
    [string appendFormat:@"translatedMsg: %@", realTimeSubtitle.translatedMsg];
    HWMConfCtrlTableViewCell *cell = [self.tableView.listView viewAtColumn:0 row:HWMConfCtrlCellTypeRealTimeSubtitleInfoNotify makeIfNecessary:YES];
    cell.notifyLabel.stringValue = string;
}

/// 字幕记录消息通知
- (void)onSubtitleRecordNotify:(HWMSDKSubtitleRecordInfoModel *)subtitleInfo {
    [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"字幕记录消息通知: %@", [subtitleInfo yy_modelDescription]];
}

/// 本地录制操作中断通知
- (void)onStartLocalRecordOperationInterruptNotify:(HWMUISDKInterruptInfoModel *)info {
    [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"本地录制操作中断通知: %@", [info yy_modelDescription]];
}

@end
