import _ from 'lodash';
import PropTypes from 'prop-types';
import React from 'react';
import Suggest from 'ui-components/lib/Suggest';
import Unit from 'ui/Unit';

import SuggestService from 'services/suggest';
import ConfigStore from 'stores/Config';
import AuthStore from 'stores/Auth';
import template from 'lib/template';
import Url from 'lib/Url';
import { i18n } from 'lib/i18n';

import './index.css';

const Search = React.createClass({

    /**
     * Получает данные для саджеста и передает их callback
     * @param {String} text
     * @param {function} next
     * @private
     */
    _getSource(text, next) {
        const { limit, type } = this.props;
        const suggestParams = { text, limit };

        if (type) {
            suggestParams.types = [type];
        }

        SuggestService.search(suggestParams, next);
    },

    _renderItem(payload) {
        const item = payload.item;
        const name = item.getAlphabeticalName ? item.getAlphabeticalName() : item.getName();

        return (
            <Unit
                size="m"
                avatar={item.getAvatar()}
                description={item.getDescription()}
                title={name}
            />
        );
    },

    _openSearchResults() {
        const query = this.refs.search.refs.input.value;
        const url = template.build(ConfigStore.get('ui.search'), {
            host: location.host,
            query: encodeURIComponent(query || '').replace(/%20/g, '+'),
            org_id: AuthStore.getOrganizationId(),
        });

        Url.open(Url.getLocation(url));
    },

    _handleKeyDown(event) {
        if (event.keyCode === 13 && !this.hasFocusedItem()) {
            this._openSearchResults();
        }
    },

    hasFocusedItem() {
        return _.get(this.refs, 'search.state.focusedIndex', -1) !== -1;
    },

    focus() {
        this.refs.search.focus();
    },

    render() {
        return (
            <div className="search__container">
                <Suggest
                    {...this.props}
                    popupClassName="search__list"
                    source={this._getSource}
                    timeout={200}
                    renderItem={this._renderItem}
                    onKeyDown={this._handleKeyDown}
                    placeholder={i18n('common.suggest_search_placeholder.default')}
                    ref="search"
                />
                <div className="search__button" onClick={this._openSearchResults} />
            </div>
        );
    },
});

Search.propTypes = {
    limit: PropTypes.number,
    type: PropTypes.oneOf(['department', 'group', 'user']),
};

Search.defaultProps = {
    limit: 3,
};

export default Search;
