import $ from 'jquery';
import _ from 'lodash';
import { PropTypes } from 'react';
import ReactDOM from 'react-dom';

import Filter from './filter';

export default class Select extends Filter {

    static get propTypes() {
        return {
            id: PropTypes.string.isRequired,
            label: PropTypes.string.isRequired,
            menu: PropTypes.any,
            onChange: PropTypes.func,
            value: PropTypes.string,
        };
    }

    componentDidMount() {
        const defaults = {
            minimumResultsForSearch: -1, // don't show the search box.
        };
        const overrides = {};
        const $filter = this.get$Input();
        $filter.auiSelect2(_.extend(defaults, this.props.menu, overrides));
        $filter.on('change', () => this.props.onChange());
    }

    shouldComponentUpdate() {
        return false;
    }

    get$Input() {
        return $(ReactDOM.findDOMNode(this)).children('select');
    }

    render() {
        return (
            <li>
                <label htmlFor={this.props.id} className="assistive">{this.props.label}</label>
                <select id={this.props.id} value={this.props.value} readOnly>
                    {this.props.menu.items.map(item => {
                        return <option key={item.id} value={item.id} disabled={item.disabled}>{item.text}</option>;
                    })}
                </select>
            </li>
        );
    }

    value() {
        return this.props.value;
    }

    domValue() {
        return this.get$Input().val();
    }

    reset() {
        const $filter = this.get$Input();
        $filter.select2('val', this.props.menu.items[0].id);
        return $.Deferred().resolve();
    }
}
