/// <reference path="./definition.d.ts" />

import * as React from 'react';
import classNames from 'classnames';
import Hammmer from 'react-hammerjs';
import FormCore from '../form/core';

const prefix = 'tsp-component-Point';
class Point extends React.Component<TspComponentPointProps, TspComponentPointState> {
  constructor(props: TspComponentPointProps, state: TspComponentPointState) {
    super(props, state);
    this.onClick = this.onClick.bind(this);
  }

  /**
   * 个数
   */
  private count: number[] = [];
  /**
   * FormCore 实例
   */
  private formCore: FormCore;

  public state: TspComponentPointState = {
    value: this.props.defaultValue
  };

  public componentWillMount(): void {
    for (let i = 0; i < this.props.count; i++) {
      this.count.push(i);
    }
  }

  public componentDidMount(): void {
    this.formCore = new FormCore({
      elem: this.refs.elem as HTMLElement,
      required: this.props.required,
      defaultValue: this.props.defaultValue.toString()
    });
  }

  public shouldComponentUpdate(nextProps: TspComponentPointProps, nextState: TspComponentPointState): boolean {
    return this.state.value !== nextState.value;
  }

  public componentWillReceiveProps(nextProps: TspComponentPointProps): void {
    if (this.props.defaultValue !== nextProps.defaultValue) {
      this.setState({
        value: nextProps.defaultValue
      });
    }
  }

  public onClick(i: number): void {
    if (!this.props.disabled) {
      this.setState({
        value: i
      });
      if (this.props.onClick) {
        this.props.onClick(i);
      }
      this.formCore.elem.dataset.value = i.toString();
    }
  }

  public render(): JSX.Element {
    return (
      <div
        id={this.props.id}
        className={classNames({
          [prefix]: true,
          [this.props.className]: this.props.className
        })}
        ref="elem"
      >
        {this.count.map((value, i) => (
          <Hammmer onTap={() => this.onClick(i + 1)} key={i}>
            <div
              className={classNames({
                [`${prefix}-item`]: true,
                [`${prefix}-item-current`]: i < this.state.value
              })}
            >
              {i < this.state.value ? this.props.currentIcon : this.props.icon}
            </div>
          </Hammmer>
        ))}
      </div>
    );
  }
};

export default Point;