import React from 'react';
import { POSITION_TOP, POSITION_BOTTOM } from 'react-svg-pan-zoom';

interface IToolbarButtonProps {
  title: string
  name: string
  toolbarPosition: string
  activeColor: string
  onClick: (event: React.MouseEvent | React.TouchEvent) => void
  active: boolean
  children: JSX.Element | JSX.Element[]
}

interface IToolbarButtonState {
  hover: boolean
}

export class ToolbarButton extends React.Component<IToolbarButtonProps, IToolbarButtonState> {
  public state: IToolbarButtonState;

  constructor(props: IToolbarButtonProps) {
    super(props);
    this.state = { hover: false };
  }

  change(event: (React.MouseEvent | React.TouchEvent)): void {
    event.preventDefault();
    event.stopPropagation();

    switch (event.type) {
      case 'mouseenter':
      case 'touchstart':
        this.setState({ hover: true });
        break;
      case 'mouseleave':
      case 'touchend':
      case 'touchcancel':
        this.setState({ hover: false });
        break;
      default:
        // noop
    }
  }

  render(): JSX.Element {
    const style = {
      display: 'block',
      width: '24px',
      height: '24px',
      margin: [POSITION_TOP, POSITION_BOTTOM].includes(this.props.toolbarPosition)
        ? '2px 1px'
        : '1px 2px',
      color: this.props.active || this.state.hover
        ? this.props.activeColor
        : '#FFF',
      transition: 'color 200ms ease',
      background: 'none',
      padding: '0px',
      border: '0px',
      outline: '0px',
      cursor: 'pointer'
    };

    return (
      <button
        onMouseEnter={e => { this.change(e); }}
        onMouseLeave={e => { this.change(e); }}

        onTouchStart={e => {
          this.change(e);
          this.props.onClick(e);
        }}
        onTouchEnd={e => { this.change(e); }}
        onTouchCancel={e => { this.change(e); }}

        onClick={this.props.onClick}

        style={style}
        title={this.props.title}
        name={this.props.name}
        type="button"
      >{this.props.children}</button>
    );
  }
}
