import React from 'react';
import PropTypes from 'prop-types';
import Textfield from '../atoms/Textfield';
import newId from '../utils/newId';

export default class FilterTextField extends React.Component {

  constructor(props) {
    super(props);
    this.onChange = this.onChange.bind(this);
  }

  componentWillMount() {
    // We need some way to identify ourselves to the Toolbar.Filter component keeping track of active filters.
    this.id = newId();
    this.updateActiveState(this.props.value);
  }

  componentWillUnmount() {
    if (this.context.setFilterActive) {
      this.context.setFilterActive(this.id, false);
    }
  }

  onChange(e) {
    this.updateActiveState(e.target.value);
    if (this.props.onChange) this.props.onChange(e);
  }

  updateActiveState(value) {
    const active = !!value;
    // Notify the parent Toolbar.Filter component with our new active state.
    if (this.context.setFilterActive) {
      this.context.setFilterActive(this.id, active);
    }
  }

  render() {
    return (
      <Textfield
        {...this.props}
        onChange={this.onChange}
      />
    );
  }
}

FilterTextField.contextTypes = {
  setFilterActive: PropTypes.func
};
