import React, { Component } from 'react';
import { Menu } from 'antd';
import { MenuEntity, MenuNode } from 'matrix-ui-service';
import { Icon } from '../common';
import { ItemType } from 'antd/es/menu/hooks/useItems';

const SubMenu = Menu.SubMenu;

export interface MenuClickHandler {
  (menu: MenuEntity): void;
}

interface P {
  rootMenu: MenuNode;
  menuClick: MenuClickHandler;
}

export class MenuTree extends Component<P> {
  render() {
    const { rootMenu } = this.props;
    return (
      <Menu
        theme="light"
        defaultSelectedKeys={['1']}
        mode="inline"
        items={rootMenu.subMenus.map((menuNode) => getTree(menuNode, this.props.menuClick))}
      ></Menu>
    );
  }
}

function getTree(menuNode: MenuNode, clickHandle: MenuClickHandler): ItemType {
  const { app, id, label } = menuNode.menu;
  const icon = <Icon type={menuNode.menu.icon} />;
  if (app) {
    const onClick = clickHandle.bind(null, menuNode.menu);
    return { key: id, icon, onClick, label };
  } else {
    const label = (
      <span>
        <Icon type={menuNode.menu.icon} />
        <span>{menuNode.menu.label}</span>
      </span>
    );
    const children = menuNode.subMenus.map((subNode) => getTree(subNode, clickHandle));
    return { key: id, children, label };
  }
}
