//
//  HWMToolBarConfigDataSource.m
//  HWMUISDKNativeDemo
//
//  Created by tyfinal on 2021/6/28.
//  Copyright © 2021 Huawei Technologies Co. Ltd. All rights reserved.
//

#import "HWMToolBarConfigDataSource.h"
#import <HWMUISDK/HWMMenuItemModel.h>

@interface HWMToolBarConfigDataSource ()
{
}
@property (nonatomic, strong) NSArray *toolBar;
@property (nonatomic, strong) NSArray *shareBar;
@property (nonatomic, strong) NSArray *toolBarMore;
@property (nonatomic, strong) NSArray *shareBarMore;

@end

@implementation HWMToolBarConfigDataSource

+ (instancetype)shareInstance {
    static dispatch_once_t onceToken;
    static HWMToolBarConfigDataSource *instace;
    dispatch_once(&onceToken, ^{
        if (!instace) {
            instace = [[self alloc]init];
        }
    });
    return instace;
}

- (void)setItemConfig:(HWMToolBarItemConfig)itemConfig {
    _itemConfig = itemConfig;
}

#pragma mark - Inner config

// 自定义按钮
- (HWMToolBarItemModel *)customItem {
    HWMToolBarItemModel *customModel = [[HWMToolBarItemModel alloc]init];

    // hoveredTitle hignlightedTitle selectedTitle 为可选项 不传时默认使用title的值
    customModel.title = @"自定义";
    customModel.selectedTitle = @"选中自定义";

    // 小图标 hoveredIconImage hignlightedIconImage selectedIconImage 为可选项 不传时默认使用title的值
    customModel.iconImage = [NSImage imageNamed:@"icon-customize-select-normal"];
    customModel.selectedIconImage = [NSImage imageNamed:@"icon-customize-select-selected"];
    customModel.disabledIconImage = [NSImage imageNamed:@"icon-customize-select-normal"];

    customModel.ctrlType = 101;
    @weakify(customModel);
    customModel.ClickItemCallback = ^(HWMToolBarItemType ctrlType) {
        @strongify(customModel);
        [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"点击了 %@ ctrlType = %ld", customModel.title, ctrlType];
    };
    return customModel;
}

// 带二级菜单按钮定制
- (HWMToolBarItemModel *)customItemWithMenus {
    HWMToolBarItemModel *customModel = [[HWMToolBarItemModel alloc]init];
    customModel.title = @"菜单";
    customModel.iconImage = [NSImage imageNamed:@"head_icon_1"];
    
    HWMMenuItemModel *headlineItem = [[HWMMenuItemModel alloc]init];
    headlineItem.themeLevel = HWMToolBarMenuItemThemeLevelHeading;
    headlineItem.title = @"菜单自定义";
    headlineItem.needSeperator = YES;
    
    HWMMenuItemModel *item = [[HWMMenuItemModel alloc]init];
    item.title = @"无二级菜单";
    @weakify(item);
    item.clickHandler = ^{
        @strongify(item);
        [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"点击了 %@",item.title];
    };
    
    customModel.submenus = @[headlineItem,[self supportSubmenuItem],item];
    return customModel;
}

// 修改默认按钮属性
- (HWMToolBarItemModel *)modifyItem {
    HWMToolBarItemModel *securityItem = [HWMToolBarItemModel defaultSecurityItem];
    securityItem.title = @"修改标题";
    @weakify(securityItem);
    securityItem.ClickItemCallback = ^(HWMToolBarItemType ctrlType) {
        @strongify(securityItem);
        [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"点击了 %@ ctrlType = %ld", securityItem.title, ctrlType];
    };
    return securityItem;
}

// 带子菜单项的菜单定制
- (HWMMenuItemModel *)supportSubmenuItem {
    HWMMenuItemModel *menuItem = [[HWMMenuItemModel alloc]init];
    // 默认为 WKCFToolBarMenuItemThemeLevelTitle 可以不设置
    menuItem.themeLevel = HWMToolBarMenuItemThemeLevelTitle;
    menuItem.allowSelected = YES;
    menuItem.selected = YES;
    // allowSelected为YES时 设置selected 为NO时 展示image 为YES时展示 selectedImage。不传将使用默认图片
    // allowSelected为NO时 image有值时 在文字前展示该图片
    menuItem.image = [NSImage imageNamed:@"icon-customize-select-normal"];
    menuItem.selectedImage = [NSImage imageNamed:@"iconMeeting"];
    menuItem.title = @"自定义菜单项";
    // 仅在themeLevel为WKCFToolBarMenuItemThemeLevelTitle时 设置文字颜色才生效
    menuItem.titleColor = [NSColor redColor];
    NSMutableArray *submenuMu = @[].mutableCopy;
    for (NSInteger i = 0; i < 4; i++) {
        HWMMenuItemModel *submenuItem = [[HWMMenuItemModel alloc]init];
        submenuItem.title = [NSString stringWithFormat:@"子菜单项%ld", i];
        @weakify(submenuItem);
        submenuItem.clickHandler = ^{
            @strongify(submenuItem);
            [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"点击了%@", submenuItem.title];
        };
        [submenuMu addObject:submenuItem];
    }
    menuItem.submenus = submenuMu;
    return menuItem;
}

// 底部工具栏左边区域 如果需要隐藏所有按钮 则传空数组
- (NSArray *)leadingItems {
    return @[[HWMToolBarItemModel defaultMicrophoneItem],
             [HWMToolBarItemModel defaultSpeakerItem]];
}

// 底部工具栏左边区域 如果需要隐藏所有按钮 则传空数组
- (NSArray *)centerItems {
    return @[[HWMToolBarItemModel defaultSecurityItem],
             [HWMToolBarItemModel defaultInvitationItem],
             [HWMToolBarItemModel defaultParticipantItem],
             [HWMToolBarItemModel defaultDataShareItem],
             [self customItemWithMenus],
             [self customItem],
             [HWMToolBarItemModel defaultMoreItem]];
}

// 底部工具栏左边区域 如果需要隐藏所有按钮 则传空数组
- (NSArray *)trailingItems {
    return @[[HWMToolBarItemModel defaultLeaveItem]];
}

// 共享按钮配置
- (NSArray *)shareToolBarItemModelArray {
    return @[[HWMToolBarItemModel defaultMicrophoneItem],
             [HWMToolBarItemModel defaultSpeakerItem],
             [HWMToolBarItemModel defaultCameraItem],
             [HWMToolBarItemModel defaultParticipantItem],
             [HWMToolBarItemModel defaultChatItem],
             [self modifyItem]];
}

// 会控更多菜单
- (NSArray *)moreMenuItemModelArray {
    return @[[HWMMenuItemModel defaultSubtitleModel],
             [HWMMenuItemModel defaultFeedbackModel],
             [HWMMenuItemModel defaultNetworkDectectionModel],
             [HWMMenuItemModel defaultSmallPaneModel],
             [self supportSubmenuItem]];
}

// 共享更多菜单
- (NSArray *)shareMoreModelArray {
    return @[[HWMMenuItemModel defaultSecurityModel],
             [HWMMenuItemModel defaultInvitationModel],
             [HWMMenuItemModel defaultSubtitleModel],
             [HWMMenuItemModel defaultFeedbackModel],
             [HWMMenuItemModel defaultNetworkDectectionModel],
             [HWMMenuItemModel defaultLeaveMeetingModel]];
}

#pragma mark - HWMConfCtrlItemHandler

- (nullable NSArray <NSArray <HWMToolBarItemModel *> *> *)meetingToolBarItemsForScene:(HWMConfToolBarScene)scene {
    if (_itemConfig == HWMToolBarItemConfigDefault) {
        return nil;
    } else if (_itemConfig == HWMToolBarItemConfigReceiveInput) {
        return _toolBar;
    } else {
        NSArray *items = @[[self leadingItems],
                           [self centerItems],
                           [self trailingItems]];
        return items;
    }
}

- (nullable NSArray <HWMToolBarItemModel *> *)screenShareToolBarItems {
    if (_itemConfig == HWMToolBarItemConfigDefault) {
        return nil;
    } else if (_itemConfig == HWMToolBarItemConfigReceiveInput) {
        return _shareBar;
    } else {
        return [self shareToolBarItemModelArray];
    }
}

// 可通过定制 HWMToolBarItemModel submenus实现 该代理方法后续将移除
- (nullable NSArray <HWMMenuItemModel *> *)meetingToolbarMoreMenuItems {
    if (_itemConfig == HWMToolBarItemConfigDefault) {
        return nil;
    } else if (_itemConfig == HWMToolBarItemConfigReceiveInput) {
        return _toolBarMore;
    } else {
        return [self moreMenuItemModelArray];
    }
}

// 可通过定制 HWMToolBarItemModel submenus实现 该代理方法后续将移除
- (nullable NSArray <HWMMenuItemModel *> *)screenShareToolbarMoreMenuItems {
    if (_itemConfig == HWMToolBarItemConfigDefault) {
        return nil;
    } else if (_itemConfig == HWMToolBarItemConfigReceiveInput) {
        return _shareBarMore;
    } else {
        return [self shareMoreModelArray];
    }
}

- (void)setConfigModel:(HWMItemConfigModel *)configModel {
    _configModel = configModel;
    _toolBar = [self generateToolBarItemsWithArray:configModel.toolBar];
    _shareBar = [self generateBarItemsWithArray:configModel.shareBar];
    _toolBarMore = [self generateMenuItemsWithModelArray:configModel.toolBarMore];
    _shareBarMore = [self generateMenuItemsWithModelArray:configModel.shareBarMore];
}

- (nullable NSArray *)generateToolBarItemsWithArray:(nullable NSArray *)modelArray {
    if (modelArray.count > 0) {
        NSMutableArray *mu = @[].mutableCopy;
        for (NSArray *array in modelArray) {
            NSArray *itemArray = [self generateBarItemsWithArray:array];
            if (itemArray) {
                [mu addObject:itemArray];
            } else {
                [mu addObject:@[]];
            }
        }
        return mu.copy;
    }
    return nil;
}

// 将输入框中输入的数据源转化为 HWMToolBarItemModel数组
- (NSArray *)generateBarItemsWithArray:(NSArray *)modelArray {
    if (modelArray.count > 0) {
        HWMToolBarItemModel *model;
        SEL sel;
        NSMutableArray *subarrayMu = @[].mutableCopy;
        for (HWMItemConfigSubmodel *submodel in modelArray) {
            NSSelectorFromString(submodel.defaultConfig);
            sel = NSSelectorFromString(submodel.defaultConfig);
            if (submodel.defaultConfig) {
                if ([HWMToolBarItemModel respondsToSelector:sel]) {
                    model = [HWMToolBarItemModel performSelector:sel];
                }
            } else {
                model = [[HWMToolBarItemModel alloc] init];
            }
            model.selected = submodel.selected;
            
            if (!submodel.useDefaultConfig.boolValue && model) {
                if (submodel.title.length > 0) {
                    model.title = submodel.title;
                }
                
                if (submodel.selectedTitle.length) {
                    model.selectedTitle = submodel.selectedTitle;
                }
                
                if (submodel.disabledTitle.length) {
                    model.disabledTitle = submodel.disabledTitle;
                }
                
                if (submodel.defaultTitle.length) {
                    model.defaultTitle = submodel.defaultTitle;
                }
                
                NSImage *img = [self imageWithImagePath:submodel.imagePath];
                if (img) {
                    [model setIconImage:img];
                }
                NSImage *disabledImg = [self imageWithImagePath:submodel.disabledImagePath];
                if (disabledImg) {
                    [model setDisabledIconImage:disabledImg];
                }

                NSImage *selectedImg = [self imageWithImagePath:submodel.selectedImagePath];
                if (selectedImg) {
                    model.selectedIconImage = selectedImg;
                }

                NSImage *defaultImg = [self imageWithImagePath:submodel.defaultImagePath];
                if (defaultImg) {
                    model.defaultIconImage = defaultImg;
                }
                
                NSImage *lockImg = [self imageWithImagePath:submodel.lockImagePath];
                if (lockImg) {
                    model.lockIconImage = lockImg;
                }
                
                if (submodel.type.length) {
                    [(HWMToolBarItemModel *) model setCtrlType:submodel.type.integerValue];
                }
                
                if (submodel.submenus.count > 0) {
                    model.submenus = [self generateMenuItemsWithModelArray:submodel.submenus];
                }
                
                if (submodel.useCustomEvent.boolValue) {
                    @weakify(self);
                    [(HWMToolBarItemModel *)model setClickItemCallback:^(HWMToolBarItemType ctrlType) {
                        @strongify(self);
                        [self clickItemWithType:ctrlType title:submodel.title];
                    }];
                }
            }
            if (model) {
                [subarrayMu addObject:model];
            }
        }
        return subarrayMu.copy;
    } else {
        return nil;
    }
}

// 将输入框中输入的数据源转化为 HWMMenuItemModel数组
- (nullable NSArray *)generateMenuItemsWithModelArray:(nullable NSArray *)modelArray {
    if (modelArray.count > 0) {
        HWMMenuItemModel *model;
        SEL sel;
        NSMutableArray *mu = @[].mutableCopy;
        for (HWMMenuConfigSubmodel *configModel in modelArray) {
            if (configModel.defaultConfig.length > 0) {
                sel = NSSelectorFromString(configModel.defaultConfig);
                if ([HWMMenuItemModel respondsToSelector:sel]) {
                    model = [HWMMenuItemModel performSelector:sel];
                }
            } else {
                model = [[HWMMenuItemModel alloc] init];
            }
            if (!configModel.useDefaultConfig.boolValue && model) {
                if (configModel.title.length > 0) model.title = configModel.title;
                NSImage *img = [self imageWithImagePath:configModel.imagePath];
                model.themeLevel = configModel.themeLevel;
                model.selected = configModel.selected;
                if (img) {
                    model.image = img;
                }
                NSImage *selectedImg = [self imageWithImagePath:configModel.selectedImagePath];
                if (selectedImg) {
                    model.selectedImage = selectedImg;
                }
                model.allowSelected = configModel.allowSelected;
                model.needSeperator = configModel.needSeperator;

                if (configModel.useCustomEvent.boolValue) {
                    @weakify(self);
                    model.clickHandler = ^{
                        @strongify(self);
                        [self clickCustomMenuItemEventWithTitle:configModel.title];
                    };
                }
                if (configModel.submenus.count > 0) {
                    model.submenus = [self generateMenuItemsWithModelArray:configModel.submenus];
                }
            }
            if (model) {
                [mu addObject:model];
            }
        }
        return mu.copy;
    }
    return nil;
}

- (nullable NSImage *)imageWithImagePath:(nullable NSString *)imgPath {
    if (imgPath.length > 0) {
        NSImage *img = [[NSImage alloc]initWithContentsOfFile:[NSString stringWithFormat:@"%@/Documents/%@", NSHomeDirectory(), imgPath]];
        if (!img) {
            img = [NSImage imageNamed:imgPath];
        }
        return img;
    }
    return nil;
}

- (void)clickItemWithType:(HWMToolBarItemType)type title:(NSString *)title {
    [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"click item %@ type = %ld", title, type];
}

- (void)clickCustomMenuItemEventWithTitle:(NSString *)title {
    [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"click menu item %@", title];
}

@end
