import * as React from 'react';

import { ColorNames } from '../types/ITheme';
import { globalColors } from '../theme/themeData';

export const sizes = {
  xs: {
    width: '20px',
    height: '20px'
  },
  md: {
    width: '30px',
    height: '30px'
  },
  lg: {
    width: '40px',
    height: '40px'
  }
};

export interface IIconProps {
  fill?: ColorNames;
  hoverFill?: ColorNames;
  width?: string;
  height?: string;
  size?: keyof typeof sizes;
}

export interface IIconState {
  isHover: boolean;
}

export const withIcon = (Component: any) => {
  return class extends React.Component<IIconProps, IIconState> {
    state = {
      isHover: false
    };

    constructor(props: IIconProps) {
      super(props);
      this.handleHover = this.handleHover.bind(this);
    }

    handleHover() {
      if (!this.props.hoverFill) {
        // do nothing if hoverFill is not specified
        return;
      }
      this.setState(state => ({
        isHover: !state.isHover
      }));
    }

    getHeight() {
      const { height, size } = this.props;
      if (size) {
        return sizes[size].height;
      }
      if (height) {
        return height;
      }
      return sizes.md.height;
    }

    getWidth() {
      const { width, size } = this.props;
      if (size) {
        return sizes[size].width;
      }
      if (width) {
        return width;
      }
      return sizes.md.width;
    }

    getFill() {
      const { fill } = this.props;
      if (this.state.isHover && fill) {
        const color = globalColors[fill];
        return `${color.substring(0, color.lastIndexOf(','))}, 0.5)`;
      }
      return globalColors[fill || 'black'];
    }

    render() {
      return (
        <Component
          height={this.getHeight()}
          width={this.getWidth()}
          fill={this.getFill()}
          onMouseEnter={this.handleHover}
          onMouseLeave={this.handleHover}
        />
      );
    }
  };
};
