import React from "react";
import { connect } from "redux-bundler-react";
import classnames from "classnames";

class BasicToolbarButton extends React.Component {
  constructor(props) {
    super(props);

    this.renderIcon = this.renderIcon.bind(this);
    this.toggleTool = this.toggleTool.bind(this);
  }

  toggleTool() {
    const {
      enabled,
      title,
      onActivate,
      onDeactivate,
      basicToolbarActiveTool,
      doBasicToolbarToggle,
    } = this.props;

    if (!enabled) return;

    doBasicToolbarToggle(basicToolbarActiveTool, title);
    if (onActivate) onActivate();
    if (onDeactivate) onDeactivate();
  }

  renderIcon() {
    const {
      children,
      text,
      title,
      iconClass,
      iconStyle,
      basicToolbarActiveTool,
      dropup,
      themeIconSize,
    } = this.props;

    const btnClass = classnames({
      "cm-nav-btn": true,
      "cm-nav-icon": themeIconSize === "default" ? true : false,
      "cm-nav-icon-lg": themeIconSize === "large" ? true : false,
      "basic-toolbar-btn": true,
      "cm-dropdown-toggle": true,
      active: basicToolbarActiveTool === title,
    });

    const arrowIcon = classnames({
      mdi: true,
      "mdi-menu-down": !dropup,
      "mdi-menu-up": dropup,
    });

    if (children) {
      return (
        <div onClick={this.toggleTool} className={btnClass}>
          <i className={iconClass} style={iconStyle} />
          {text}
          <i className={arrowIcon} />
        </div>
      );
    } else {
      return (
        <div
          onClick={this.toggleTool}
          className={btnClass}
          style={{ textAlign: "center" }}
        >
          <i className={iconClass} style={iconStyle} />
          {text}
        </div>
      );
    }
  }

  render() {
    const {
      theme,
      basicToolbarActiveTool,
      title,
      children,
      dropup,
      passProps,
      basicToolbarOpen,
    } = this.props;

    const canOpen =
      basicToolbarOpen && basicToolbarActiveTool === title ? true : false;

    const btnContainerClass = classnames({
      [theme]: true,
      "cm-btn-group": true,
      open: canOpen,
    });

    const activeClass = classnames({
      "basic-toolbar-btn-active": !dropup,
      "basic-toolbar-btn-active-top": dropup,
      hidden: !(basicToolbarActiveTool === title),
    });

    return (
      <div className={btnContainerClass} {...passProps} title={title}>
        <div className={activeClass} />
        {this.renderIcon()}
        {children}
      </div>
    );
  }
}

export default connect(
  "selectTheme",
  "selectThemeIconSize",
  "selectBasicToolbarActiveTool",
  "selectBasicToolbarOpen",
  "doBasicToolbarActivate",
  "doBasicToolbarDeactivate",
  "doBasicToolbarToggle",
  BasicToolbarButton
);
