'use strict';
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importDefault(require("react"));
var prop_types_1 = __importDefault(require("prop-types"));
var lodash_1 = __importDefault(require("lodash"));
var FormControl_1 = require("./FormControl");
var react_autosuggest_1 = __importDefault(require("react-autosuggest"));
var TextInputControl_1 = require("./TextInputControl");
var utils_1 = require("../list/utils");
var Store_1 = require("../../data/Store");
var playMessage_1 = require("../../utils/playMessage");
var utils_2 = require("../../../utils");
var index_en_US_1 = __importDefault(require("../../../lang/common/index-en_US"));
var ENTER_CHAR_CODE = 13;
var READ_KEY_DOWN_TIMEOUT = 1000;
var AutosuggestControl = /** @class */ (function (_super) {
    __extends(AutosuggestControl, _super);
    function AutosuggestControl(props, context) {
        var _this = _super.call(this, props, context) || this;
        _this.handleFocus = function () {
            _this.setState({ isInputFocused: true });
        };
        _this.handleBlur = function (event) {
            _this.onSubmitChanges(event.target.value);
            _this.setState({ isInputFocused: false });
        };
        _this.playSuggestionPromptMessage = lodash_1.default.debounce(function (count) {
            var isInputFocused = _this.state.isInputFocused;
            if (!isInputFocused) {
                return;
            }
            var _a = _this.props, suggestionPromptLabel = _a.suggestionPromptLabel, noSuggestionPromptLabel = _a.noSuggestionPromptLabel;
            var message = count === 0
                ? utils_2.translate(noSuggestionPromptLabel, { count: count })
                : utils_2.translate(suggestionPromptLabel, { count: count });
            playMessage_1.playMessage(message);
        }, READ_KEY_DOWN_TIMEOUT);
        _this.filterSuggestions = function (query, values) {
            if (query.length >= _this.props.minCharactersToShowSuggestions) {
                var regex_1 = Store_1.Store.searchStringToRegExp(query);
                var filteredValues = values.filter(function (value) {
                    regex_1.lastIndex = 0;
                    return regex_1.test(_this.props.getSuggestionText(value));
                });
                return lodash_1.default.take(filteredValues, _this.props.maxSuggestionsCount);
            }
            return [];
        };
        _this.renderInputComponent = function (props) { return react_1.default.createElement(TextInputControl_1.TextInputControl, __assign({}, props)); };
        _this.renderSuggestionsContainer = function (renderOptions) {
            var containerProps = renderOptions.containerProps, children = renderOptions.children;
            return (react_1.default.createElement("div", __assign({}, containerProps, { role: null }), children));
        };
        var propsFromContext = _this.getPropsFromContext();
        _this.state = {
            suggestions: [],
            isInputFocused: false,
            value: propsFromContext.value
                ? propsFromContext.getSuggestionValue(propsFromContext.value)
                : ''
        };
        return _this;
    }
    AutosuggestControl.prototype.componentWillReceiveProps = function (nextProps) {
        var propsFromContext = this.getPropsFromContext();
        if (nextProps.value !== undefined) {
            this.setState({
                value: nextProps.value === null
                    ? ''
                    : propsFromContext.getSuggestionValue(nextProps.value)
            });
        }
    };
    AutosuggestControl.prototype.componentDidUpdate = function (oldProps, oldState) {
        _super.prototype.componentDidUpdate.call(this, oldProps, oldState);
        var getCount = function (list) { return (lodash_1.default.isEmpty(list) ? 0 : list.length); };
        var oldSuggestions = oldState.suggestions;
        var suggestions = this.state.suggestions;
        var oldCount = getCount(oldSuggestions);
        var newCount = getCount(suggestions);
        if (oldCount !== newCount) {
            this.playSuggestionPromptMessage(newCount);
        }
    };
    AutosuggestControl.prototype.onChange = function (event, _a) {
        var newValue = _a.newValue;
        this.setState({
            value: newValue
        });
        this.props.onInputChange(newValue);
    };
    AutosuggestControl.prototype.onSubmitChanges = function (newValue) {
        var _this = this;
        var values = this.props.values || this.state.suggestions || [];
        var propsFromContext = this.getPropsFromContext();
        var matchedValue = values.find(function (value) {
            return _this.props.valueMatcher.call(_this, newValue, value);
        });
        var allowMismatching = this.props.allowMismatching || this.props.getSuggestions;
        var mismatchedValue = allowMismatching ? newValue : '';
        this.setState({
            value: matchedValue
                ? propsFromContext.getSuggestionValue(matchedValue)
                : mismatchedValue
        });
        var updateValue = matchedValue || mismatchedValue || null;
        propsFromContext.onChange(updateValue);
        if (lodash_1.default.isFunction(this.props.onSubmitChanges)) {
            this.props.onSubmitChanges(updateValue);
        }
    };
    AutosuggestControl.prototype.onKeyPress = function (event) {
        if (event.charCode === ENTER_CHAR_CODE) {
            this.onSubmitChanges(event.target.value);
        }
    };
    AutosuggestControl.prototype.onSuggestionSelected = function (event, _a) {
        var suggestionValue = _a.suggestionValue;
        this.onSubmitChanges(suggestionValue);
    };
    AutosuggestControl.prototype.onSuggestionsFetchRequested = function (_a) {
        var _this = this;
        var value = _a.value;
        return Promise.resolve(this.getSuggestions(value)).then(function (suggestions) {
            return _this.setState({ suggestions: suggestions });
        });
    };
    AutosuggestControl.prototype.onSuggestionsClearRequested = function () {
        this.setState({
            suggestions: []
        });
    };
    AutosuggestControl.prototype.getSuggestions = function (query) {
        var _this = this;
        if (lodash_1.default.isFunction(this.props.getSuggestions)) {
            return this.props.getSuggestions(query, 
            /**innerFilter*/ function (values) { return _this.filterSuggestions(query, values); });
        }
        return this.filterSuggestions(query, this.props.values);
    };
    AutosuggestControl.prototype.renderSuggestion = function (value, _a) {
        var query = _a.query;
        var regex = Store_1.Store.searchStringToRegExp(query);
        regex.lastIndex = 0;
        return utils_1.highlight(regex, this.props.getSuggestionText(value));
    };
    AutosuggestControl.prototype.render = function () {
        var suggestions = this.state.suggestions;
        var inputProps = {
            placeholder: this.props.placeholder,
            name: this.props.name,
            onChange: this.onChange.bind(this),
            value: this.state.value,
            disabled: this.props.disabled,
            onBlur: this.handleBlur,
            onFocus: this.handleFocus,
            onKeyPress: this.onKeyPress.bind(this),
            autoFocus: this.props.autoFocus,
            maxLength: this.props.maxLength
        };
        var ariaDescId = this.props['aria-describedby'];
        if (ariaDescId) {
            inputProps['aria-describedby'] = ariaDescId;
        }
        var ariaLabel = this.props['aria-label'];
        if (ariaLabel) {
            inputProps['aria-label'] = ariaLabel;
        }
        var theme = {
            container: 'autosuggest-container',
            containerOpen: 'autosuggest-container-open',
            input: 'autosuggest-input',
            suggestionsContainer: 'autosuggest-suggestions-container',
            suggestionsList: 'autosuggest-suggestions-list',
            suggestion: 'autosuggest-suggestion',
            itemHighlighted: 'autosuggest-suggestion-focused',
            sectionContainer: 'autosuggest-section-container',
            sectionTitle: 'autosuggest-section-title'
        };
        return (react_1.default.createElement(react_autosuggest_1.default, { ref: "autoSuggest", suggestions: suggestions, onSuggestionsFetchRequested: this.onSuggestionsFetchRequested.bind(this), onSuggestionsClearRequested: this.onSuggestionsClearRequested.bind(this), getSuggestionValue: this.props.getSuggestionValue.bind(this), onSuggestionSelected: this.onSuggestionSelected.bind(this), renderSuggestion: this.renderSuggestion.bind(this), renderInputComponent: this.renderInputComponent, renderSuggestionsContainer: this.renderSuggestionsContainer, inputProps: inputProps, theme: theme }));
    };
    AutosuggestControl.propTypes = __assign({}, FormControl_1.FormControl.propTypes, { 
        /* if getSuggestions() is provided values is not necessary */
        values: prop_types_1.default.array, getSuggestionValue: prop_types_1.default.func.isRequired, getSuggestionText: prop_types_1.default.func.isRequired, valueMatcher: prop_types_1.default.func, placeholder: prop_types_1.default.string, maxSuggestionsCount: prop_types_1.default.number, minCharactersToShowSuggestions: prop_types_1.default.number, disabled: prop_types_1.default.bool, allowMismatching: prop_types_1.default.bool, 
        /**
         * @function (query: String, innerFilter: function(values))
         * @returns { Array| Promise<Array>}
         * */
        getSuggestions: prop_types_1.default.func, onSubmitChanges: prop_types_1.default.func, autoFocus: prop_types_1.default.bool, onInputChange: prop_types_1.default.func, suggestionPromptLabel: prop_types_1.default.string, noSuggestionPromptLabel: prop_types_1.default.string });
    AutosuggestControl.defaultProps = __assign({}, FormControl_1.FormControl.defaultProps, { maxSuggestionsCount: 10, minCharactersToShowSuggestions: 2, valueMatcher: function (inputValue, value) {
            return inputValue === this.props.getSuggestionValue(value);
        }, allowMismatching: false, onInputChange: function (v) { return v; }, get suggestionPromptLabel() {
            return index_en_US_1.default.AUTO_SUGGEST_SUGGESTION_PROMPT_LABEL;
        },
        get noSuggestionPromptLabel() {
            return index_en_US_1.default.NO_SUGGESTION_PROMPT_LABEL;
        } });
    return AutosuggestControl;
}(FormControl_1.FormControl));
exports.AutosuggestControl = AutosuggestControl;
//# sourceMappingURL=AutosuggestControl.js.map