/// <reference path="./definition.d.ts" />

import * as React from 'react';
import classNames from 'classnames';
import FormCore from '../form/core';
import { regexp, validatePattern } from '../util/validate';

const prefix = 'tsp-component-Input';

class Input extends React.Component<TspComponentInputProps, TspComponentInputState> {
  constructor(props: TspComponentInputProps, state: TspComponentInputState) {
    super(props, state);
    this.onChange = this.onChange.bind(this);
    this.onBlur = this.onBlur.bind(this);
  }

  private formCore: FormCore;

  public static defaultProps: TspComponentInputProps = {
    id: '',
    type: 'text',
    patternTrigger: true,
    defaultValue: '',
    emoji: true
  };

  public state: TspComponentInputState = {
    value: this.props.defaultValue
  };

  public componentDidMount(): void {
    this.formCore = new FormCore({
      elem: this.refs.elem as HTMLElement,
      required: this.props.required,
      patternType: this.props.patternType,
      pattern: this.props.pattern,
      patternTrigger: this.props.patternTrigger,
      patternMsg: this.props.patternMsg,
      defaultValue: this.props.defaultValue
    });
  }

  public componentWillReceiveProps(nextProps: TspComponentInputProps): void {
    if (this.props.defaultValue !== nextProps.defaultValue) {
      this.setState({
        value: nextProps.defaultValue
      });
      this.formCore.setValue(nextProps.defaultValue);
    }
  }

  public onChange(e: any): void {
    let value = e.target.value;

    if (this.props.emoji) {
      value = value.replace(regexp.emoji, '');
    }
    if (this.props.onChange) {
      this.props.onChange(value, e);
    }
    this.formCore.elem.dataset.value = value;
    this.setState({ value });
  }

  public onBlur(e: any): void {
    validatePattern(this.formCore.elem);
    if (this.props.onBlur) {
      this.props.onBlur(this.state.value, e);
    }
  }

  public render(): JSX.Element {
    return (
      <input
        id={this.props.id}
        className={classNames({
          [prefix]: true,
          [this.props.className]: this.props.className,
          [`${prefix}-disabled`]: this.props.disabled
        })}
        ref="elem"
        type={this.props.type}
        placeholder={this.props.placeholder}
        value={this.state.value}
        maxLength={this.props.maxLength}
        disabled={this.props.disabled}
        readOnly={this.props.readOnly}
        onChange={this.onChange}
        onBlur={this.onBlur}
      />
    );
  }
}

export default Input;
