import React from 'react';
import Proptypes from 'prop-types';
import _ from 'lodash';
import CreatableSelect from 'react-select/lib/Creatable';
import { GUI_CONFIG } from '../../../config/gui.config';

class TagSelector extends React.Component {

    constructor(props) {
        super(props);

        this.onChange = this.onChange.bind(this);
    }
    render() {
        let { availableTags } = this.props;

        // show tags inside a detailed event
        const customStyles = {
            dropdownIndicator: () => ({
                display: 'none'
            }),

            indicatorSeparator: () => ({
                display: 'none'
            }),

            control: (provided) => ({
                ...provided,
                maxWidth: 140,
                minWidth: 100,
                minHeight: 25,
            }),

            container: (provided) => ({
                ...provided,

            }),

            valueContainer: (provided) => ({
                ...provided,
                paddingTop: '0px',
                paddingBottom: '0px',
            }),

            menu: (provided) => ({
                ...provided,
                bottom: '100%',
                top: 'unset',
            })
        };

        let availableTagsForSelect = availableTags ? availableTags.map((tag) => ({ value: tag._id, label: tag.name })) : null;

        return (
            <CreatableSelect
                isClearable={false}
                noOptionsMessage={() => 'No existing tag'}
                onChange={this.onChange}
                styles={customStyles}
                options={availableTagsForSelect}
                isSearchable={true} />);
    }

    /**
     * Callback function triggered when the input has changed. A new tag is being created
     * @param {*} value the new tag as provided by the react-select component
     */
    onChange(option, action) {
        if (option && action) {
            if (action.action === 'create-option') {
                let newTag = {
                    color: GUI_CONFIG().DEFAULT_TAG_COLOR,
                    description: null,
                    name: option.label,
                    investigationId: this.props.investigationId
                };

                this.props.onTagCreatedInSelect(newTag);
            } else if (action.action === 'select-option') {
                this.props.onTagSelectedInSelect(_.find(this.props.availableTags, (tag) => { return tag._id === option.value; }));
            }
        }
    }
}

export default TagSelector;

TagSelector.proptype = {
    /** list of avialable tags */
    availableTags: Proptypes.array.isRequired,
    /** callback function triggered when a tag is created in the select element */
    onTagCreatedInSelect: Proptypes.func,
    /** Callback funnction triggered when a tag is selelcted in the select element */
    onTagSelectedInSelect: Proptypes.func
}
