//
//  HWMSettingConfigController.m
//  HWMUISDKNativeDemo
//
//  Created by linweiqiang on 2021/11/19.
//  Copyright © 2021 Huawei Technologies Co. Ltd. All rights reserved.
//

#import "HWMSettingConfigController.h"
#import "HWMSettingConfigDataSource.h"
#import "HWMTextField.h"

@interface HWMSettingConfigController () <NSTextViewDelegate>

@property (nonatomic, strong) NSTextView *textView;
@property (nonatomic, strong) NSButton *settingTabButton;
@property (nonatomic, strong) NSArray *settingTabArr;
@property (nonatomic, copy) NSString *settingTab;

@end

@implementation HWMSettingConfigController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    self.textView.string = [self convertDictionaryToJsonString:[self defaulConfig]];
}

#pragma mark - UI
- (void)setupUI {
    NSView *borderView = [[NSView alloc] init];
    borderView.wantsLayer = YES;
    borderView.layer.borderWidth = 1.0;
    borderView.layer.borderColor = [NSColor colorWithRGB:0xEEEEEE].CGColor;
    [self.view addSubview:borderView];

    NSScrollView *scrollView = [[NSScrollView alloc] init];
    scrollView.backgroundColor = [NSColor colorWithR:248 g:248 b:248];
    scrollView.autohidesScrollers = NO;
    scrollView.hasVerticalScroller = YES;
    scrollView.hasHorizontalScroller = NO;
    scrollView.verticalScrollElasticity = NSScrollElasticityAutomatic;
    scrollView.horizontalScrollElasticity = NSScrollElasticityNone;
    scrollView.wantsLayer = YES;
    scrollView.contentView.documentView = self.textView;
    [self.view addSubview:scrollView];

    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(20);
        make.leading.mas_equalTo(20);
        make.trailing.mas_equalTo(-20);
        make.height.mas_equalTo(260);
    }];
    [borderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(scrollView).insets(NSEdgeInsetsMake(-2, -2, -2, -2));
    }];

    NSButton *resetButton = [NSButton buttonWithTitle:@"使用初始默认" font:nil fontColor:[NSColor whiteColor] target:self action:@selector(clickEvent:)];
    resetButton.tag = 100;
    resetButton.layer.backgroundColor = [NSColor colorWithRGB:0x0D94FF].CGColor;
    resetButton.layer.cornerRadius = 4.0;
    resetButton.layer.masksToBounds = YES;
    [self.view addSubview:resetButton];
    [resetButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view).offset(-130);
        make.top.equalTo(scrollView.mas_bottom).offset(20);
        make.size.mas_equalTo(NSMakeSize(120, 35));
    }];

    NSButton *inputButton = [NSButton buttonWithTitle:@"使用外部输入" font:nil fontColor:[NSColor whiteColor] target:self action:@selector(clickEvent:)];
    inputButton.layer.backgroundColor = [NSColor colorWithRGB:0x0D94FF].CGColor;
    inputButton.layer.cornerRadius = 4.0;
    inputButton.layer.masksToBounds = YES;
    inputButton.tag = 101;
    [self.view addSubview:inputButton];
    [inputButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(scrollView.mas_bottom).offset(20);
        make.size.mas_equalTo(NSMakeSize(120, 35));
    }];

    NSButton *inneerButton = [NSButton buttonWithTitle:@"使用内部配置" font:nil fontColor:[NSColor whiteColor] target:self action:@selector(clickEvent:)];
    inneerButton.tag = 102;
    inneerButton.layer.backgroundColor = [NSColor colorWithRGB:0x0D94FF].CGColor;
    inneerButton.layer.cornerRadius = 4.0;
    inneerButton.layer.masksToBounds = YES;
    [self.view addSubview:inneerButton];
    [inneerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view).offset(130);
        make.top.equalTo(scrollView.mas_bottom).with.offset(20);
        make.size.mas_equalTo(NSMakeSize(120, 35));
    }];

    NSTextField *settingTabLabel = [NSTextField hwm_fieldWithTitle:@"Setting Tab" titleColor:[NSColor colorWithRGB:0x666666] font:[NSFont systemFontOfSize:13]];
    settingTabLabel.alignment = NSTextAlignmentRight;
    [self.view addSubview:settingTabLabel];
    [settingTabLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self.view.mas_centerX);
        make.top.equalTo(scrollView.mas_bottom).offset(75);
    }];

    [self.view addSubview:self.settingTabButton];
    [self.settingTabButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(settingTabLabel);
        make.leading.equalTo(settingTabLabel.mas_trailing);
    }];

    NSButton *openButton = [NSButton buttonWithTitle:@"打开会议设置" font:nil fontColor:[NSColor whiteColor] target:self action:@selector(settingEvent:)];
    openButton.tag = 200;
    openButton.layer.backgroundColor = [NSColor colorWithRGB:0x0D94FF].CGColor;
    openButton.layer.cornerRadius = 4.0;
    openButton.layer.masksToBounds = YES;
    [self.view addSubview:openButton];
    [openButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(settingTabLabel.mas_bottom).offset(20);
        make.size.mas_equalTo(NSMakeSize(300, 35));
    }];
}

#pragma mark - Event
- (void)clickEvent:(NSButton *)button {
    if (![HWMSdk hasInit]) {
        [HWMConsoleManager shareInstance].console = @"no init";
        return;
    }
    NSInteger index = button.tag - 100;
    [HWMSettingConfigDataSource sharedInstance].itemConfig = (HWMSettingItemConfig)index;
    [HWMConsoleManager shareInstance].console = @[@"use default config", @"receive input data source", @"use innner config"][index];
    if (index != 1) {
        return;
    }
    if (!self.textView.string.length) {
        [HWMConsoleManager shareInstance].console = @"input config is empty";
    } else {
        NSData *data = [self.textView.string dataUsingEncoding:NSUTF8StringEncoding];
        if (data) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            if (!dic) {
                [HWMConsoleManager shareInstance].console = @"param is nil,input config may be wrong";
            } else {
                [HWMConsoleManager shareInstance].console = @"config successfully";
                [HWMSettingConfigDataSource sharedInstance].dic = dic;
            }
        } else {
            [HWMConsoleManager shareInstance].console = @"param is nil,input config may be wrong";
        }
    }
}

- (void)settingEvent:(NSButton *)button {
    if (![HWMSdk hasInit]) {
        [HWMConsoleManager shareInstance].console = @"no init";
        return;
    }
    HWMUISDKShowSettingWindowInfoModel *model = [[HWMUISDKShowSettingWindowInfoModel alloc] init];
    model.isShow = YES;
    model.defaultPage = [self settingTabType];
    [[HWMBizSdk getBizOpenApi] showSettingWindowWithInfo:model];
    [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"show setting window and page: %ld", model.defaultPage];
}

- (void)settingTabEvent:(NSButton *)button {
    NSMenu *menu = [[NSMenu alloc] init];
    for (NSInteger i = 0; i < self.settingTabArr.count; i++) {
        NSString *title = self.settingTabArr[i];
        NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:title action:@selector(selectMenuItem:) keyEquivalent:@""];
        item.target = self;
        item.tag = i;
        [menu addItem:item];
    }
    [menu popUpMenuPositioningItem:nil atLocation:NSMakePoint(0, 24) inView:self.settingTabButton];
}

- (void)selectMenuItem:(NSMenuItem *)item {
    self.settingTab = item.title;
    NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:self.settingTab];
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    paraStyle.alignment = NSTextAlignmentCenter;
    [att addAttributes:@{ NSFontAttributeName: [NSFont systemFontOfSize:13], NSForegroundColorAttributeName: [NSColor blackColor], NSParagraphStyleAttributeName: paraStyle } range:NSMakeRange(0, self.settingTab.length)];
    self.settingTabButton.attributedTitle = att;
}

#pragma mark - Lazy
- (NSTextView *)textView {
    if (!_textView) {
        _textView = [[NSTextView alloc] initWithFrame:NSMakeRect(0, 0, 555, 111)];
        _textView.insertionPointColor = [NSColor colorWithR:102 g:102 b:102];
        _textView.backgroundColor = [NSColor whiteColor];
        _textView.richText = NO;
        _textView.delegate = self;
        _textView.autoresizingMask = NSViewHeightSizable;
        _textView.font = [NSFont systemFontOfSize:13];
        _textView.textColor = [NSColor colorWithR:51 g:51 b:51];
        _textView.textContainerInset = NSMakeSize(5, 5);
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        style.lineSpacing = 5;
        _textView.defaultParagraphStyle = style;
    }
    return _textView;
}

- (NSButton *)settingTabButton {
    if (!_settingTabButton) {
        _settingTabButton = [NSButton buttonWithTitle:self.settingTabArr.firstObject font:[NSFont systemFontOfSize:13] fontColor:[NSColor blackColor] target:self action:@selector(settingTabEvent:)];
        _settingTabButton.layer.backgroundColor = [NSColor whiteColor].CGColor;
        _settingTabButton.image = [NSImage imageNamed:@"arrow_right"];
        _settingTabButton.imagePosition = NSImageRight;
    }
    return _settingTabButton;
}

- (NSArray *)settingTabArr {
    return @[@"Normal", @"Video", @"Audio", @"Screen", @"Record", @"HotKey"];
}

- (HWMUISDKSettingPage)settingTabType {
    if ([self.settingTab isEqualToString:@"Normal"]) {
        return HWMUISDKSettingPageNormal;
    }
    if ([self.settingTab isEqualToString:@"Video"]) {
        return HWMUISDKSettingPageVideo;
    }
    if ([self.settingTab isEqualToString:@"Audio"]) {
        return HWMUISDKSettingPageAudio;
    }
    if ([self.settingTab isEqualToString:@"Screen"]) {
        return HWMUISDKSettingPageScreen;
    }
    if ([self.settingTab isEqualToString:@"Record"]) {
        return HWMUISDKSettingPageRecord;
    }
    if ([self.settingTab isEqualToString:@"HotKey"]) {
        return HWMUISDKSettingPageHotkey;
    }
    return HWMUISDKSettingPageNormal;
}

#pragma mark - Config
- (NSDictionary *)defaulConfig {
    return @{
        @"defaulTab": [self defaulSettingTabConfig],
        @"defaulHotKey": [self defaulSettingHotKeyConfig]
    };
}

- (NSArray *)defaulSettingTabConfig {
    return @[
        @{ @"type": @"defaulTabNormal",
           @"settingMenuItems": @[
               @{@"type": @"defaulMenuCall"},
               @{@"type": @"defaulMenuChatNotify"},
               @{@"type": @"defaulMenuSubtitle"},
               @{@"type": @"defaultMenuWindowFilter"}
           ]
        },
        @{ @"type": @"defaulTabVideo",
           @"settingMenuItems": @[
               @{@"type": @"defaulMenuCamera"},
               @{@"type": @"defaulMenuLayout"}]
        },
        @{ @"type": @"defaulTabAudio",
           @"settingMenuItems": @[
               @{@"type": @"defaulMenuMicrophone"},
               @{@"type": @"defaulMenuSpeaker"},
               @{@"type": @"defaulMenuAdvanced"}]
        },
        @{ @"type": @"defaulTabVirtual",
           @"settingMenuItems": @[
               @{@"type": @"defaulMenuVirtual"}]
        },
        @{ @"type": @"defaulTabScreen",
           @"settingMenuItems": @[
               @{@"type": @"defaulMenuScreen"}]
        },
        @{ @"type": @"defaulTabRecord",
           @"settingMenuItems": @[
               @{@"type": @"defaulMenuRecord"}]
        },
        @{ @"type": @"defaulTabHotKey",
           @"settingMenuItems": @[
               @{@"type": @"defaulMenuHotKey"}]
        }
    ];
}

- (NSArray *)defaulSettingHotKeyConfig {
    return @[
        @{ @"type": @"2",
           @"text": @"自定义快捷键",
           @"keyName": @"HWMHotKeyCustomKey",
           @"keyCode": @"8",
           @"action": @"action"
        }
    ];
}

- (NSString *)convertDictionaryToJsonString:(NSDictionary *)dictionary {
    if (![dictionary isKindOfClass:[NSDictionary class]] || ![NSJSONSerialization isValidJSONObject:dictionary]) {
        return nil;
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:nil];
    NSString *strJson = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return strJson;
}

@end
