import { h, Component } from 'preact';

import { bindAll, startCase } from 'lowline';

export default class Input extends Component {
  constructor(props) {
    super(props);

    bindAll(this, ['reset', 'validate', 'onChange', 'onBlur', 'onFocus']);

    this.state = {
      value: this.props.value,
    };
  }


  onChange(e) {
    e.preventDefault();

    if (document.activeElement !== e.target && !e.target.value) return;

    this.setValue(e.target.value);
  }

  onBlur(e) {
    this.setState({
      focus: false,
    });

    this.setValue(e.target.value);
  }

  onFocus() {
    this.setState({
      focus: true,
      touched: true,
    });
  }

  focus() {
    this.input.focus();
  }

  isValid() {
    this.setValue(this.input.value);

    return !this.state.error;
  }

  getValue() {
    return this.state.value;
  }

  reset() {
    this.setState({
      value: this.props.value,
    });
  }

  setValue(value) {
    value = value || undefined;

    const result = this.validate(value);

    this.setState({
      error: result !== true ? typeof result === 'string' && result || 'Error!' : false,
      value,
    });
  }

  validate(value) {
    const validation = this.validation;

    if (!validation) {
      return true;
    }

    if (validation.required) {
      if (value == null || value === '') {
        return typeof validation.required === 'string' ? validation.required : 'Required';
      }
    } else if (value == null || value === '') {
      return true;
    }

    if (!validation.tests) {
      return true;
    }

    for (let i = 0; i < validation.tests.length; i += 1) {
      const [fnc, msg] = validation.tests[i];

      if (!fnc(value)) return msg;
    }

    return true;
  }
}
