"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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
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 react_dom_1 = require("react-dom");
var lodash_1 = require("lodash");
var index_en_US_1 = __importDefault(require("../../lang/common/index-en_US"));
var functions_1 = require("../utils/functions");
var Button_1 = require("./Button");
var TextInput_1 = require("./form/TextInput");
var Icon_1 = require("./Icon");
var ELEMENT_SHOW_ALL = 'ELEMENT_SHOW_ALL';
var KEY_CODE_ENTER = 13;
var Search = /** @class */ (function (_super) {
    __extends(Search, _super);
    function Search() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            focused: false,
            focusedItem: null,
            initial: true,
            results: []
        };
        _this.resultRefs = [];
        _this.inputRef = react_1.default.createRef();
        _this.showAllRef = react_1.default.createRef();
        _this.handleFocus = function () {
            var value = _this.props.value;
            var initial = _this.state.initial;
            clearTimeout(_this.blurTimer);
            _this.setState({ focused: true });
            if (value && initial) {
                _this.search();
            }
        };
        _this.handleBlur = function () {
            _this.blurTimer = setTimeout(function () {
                _this.setState({ focused: false, focusedItem: null });
            }, 100);
        };
        _this.handleKeyboardNavigation = function (e) {
            if (_this.resultRefs.length && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
                var focusedItem = _this.state.focusedItem;
                var nextFocusedItem = void 0;
                e.stopPropagation();
                e.preventDefault();
                switch (e.key) {
                    case 'ArrowDown': {
                        if (focusedItem === null || focusedItem === ELEMENT_SHOW_ALL) {
                            nextFocusedItem = 0;
                        }
                        else if (focusedItem === _this.resultRefs.length - 1) {
                            nextFocusedItem = ELEMENT_SHOW_ALL;
                        }
                        else {
                            nextFocusedItem = focusedItem + 1;
                        }
                        break;
                    }
                    case 'ArrowUp': {
                        if (focusedItem === null || focusedItem === 0) {
                            nextFocusedItem = ELEMENT_SHOW_ALL;
                        }
                        else if (focusedItem === ELEMENT_SHOW_ALL) {
                            nextFocusedItem = _this.resultRefs.length - 1;
                        }
                        else {
                            nextFocusedItem = focusedItem - 1;
                        }
                        break;
                    }
                }
                _this.setState({ focusedItem: nextFocusedItem });
                nextFocusedItem === ELEMENT_SHOW_ALL
                    ? react_dom_1.findDOMNode(_this.showAllRef.current).focus()
                    : _this.resultRefs[nextFocusedItem].current.focus();
            }
        };
        _this.search = function () { return __awaiter(_this, void 0, void 0, function () {
            var _a, value, searchProvider, _b, _c;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        _a = this.props, value = _a.value, searchProvider = _a.searchProvider;
                        if (!value) {
                            this.setState({ results: [], initial: true });
                            return [2 /*return*/];
                        }
                        if (!(typeof searchProvider === 'function')) return [3 /*break*/, 2];
                        _b = this.setState;
                        _c = {};
                        return [4 /*yield*/, searchProvider(value)];
                    case 1:
                        _b.apply(this, [(_c.results = _d.sent(),
                                _c.initial = false,
                                _c.focusedItem = null,
                                _c)]);
                        _d.label = 2;
                    case 2: return [2 /*return*/];
                }
            });
        }); };
        _this.debouncedSearch = lodash_1.debounce(_this.search, _this.props.inputDebounce);
        _this.clear = function () {
            var onChange = _this.props.onChange;
            onChange('');
            _this.setState({ focused: false, focusedItem: null });
        };
        _this.handleChange = function (_a) {
            var target = _a.target;
            var onChange = _this.props.onChange;
            onChange(target.value);
        };
        _this.handleFullSearch = function () {
            var onSearch = _this.props.onSearch;
            if (typeof onSearch === 'function') {
                onSearch();
            }
            _this.handleBlur();
        };
        _this.handleResultAction = function (item) {
            var resultAction = _this.props.resultAction;
            if (typeof resultAction === 'function') {
                resultAction(item);
            }
            _this.handleBlur();
        };
        _this.handleEnter = function (e) {
            if (e.keyCode === KEY_CODE_ENTER && e.currentTarget.tagName === 'INPUT') {
                var $inputContainer = react_dom_1.findDOMNode(_this.inputRef.current);
                if ($inputContainer) {
                    var $input = $inputContainer.querySelector(':focus');
                    if ($input) {
                        $input.blur();
                    }
                }
                _this.handleFullSearch();
            }
        };
        _this.renderResult = function (item, index) {
            var renderResult = _this.props.renderResult;
            var handler = function () { return _this.handleResultAction(item); };
            _this.resultRefs[index] = react_1.default.createRef();
            return (react_1.default.createElement("li", { key: index, ref: _this.resultRefs[index], role: "button", className: "rc-search__result", tabIndex: -1, onClick: handler, onKeyDown: functions_1.filterKeyCodes(handler), "data-test-automation-id": "searchResult" + index }, renderResult(item)));
        };
        return _this;
    }
    Search.prototype.componentDidUpdate = function (prevProps) {
        var _a = this.props, value = _a.value, inputDebounce = _a.inputDebounce;
        if (value !== prevProps.value) {
            this.debouncedSearch(value);
        }
        if (inputDebounce !== prevProps.inputDebounce) {
            this.debouncedSearch = lodash_1.debounce(this.search, inputDebounce);
        }
    };
    Search.prototype.getResults = function () {
        var maxResults = this.props.maxResults;
        var results = this.state.results;
        if (!maxResults) {
            return results;
        }
        return results.slice(0, maxResults);
    };
    Search.prototype.renderClearButton = function () {
        var textClearLabel = this.props.textClearLabel;
        return (react_1.default.createElement("button", { className: "rc-search__action-button", onClick: this.clear, "data-test-automation-id": "searchButton", "aria-label": textClearLabel },
            react_1.default.createElement(Icon_1.Icon, { name: "close" })));
    };
    Search.prototype.renderSearchButton = function () {
        var textSearchLabel = this.props.textSearchLabel;
        return (react_1.default.createElement("button", { disabled: true, className: "rc-search__action-button", "data-test-automation-id": "searchClear", "aria-label": textSearchLabel },
            react_1.default.createElement(Icon_1.Icon, { name: "search" })));
    };
    Search.prototype.renderSearchInput = function () {
        var _a = this.props, value = _a.value, name = _a.name, textSearchPlaceholder = _a.textSearchPlaceholder;
        var focused = this.state.focused;
        var button = !focused || !value ? this.renderSearchButton() : this.renderClearButton();
        return (react_1.default.createElement("div", { className: "rc-search__input-container" },
            react_1.default.createElement(TextInput_1.TextInput, { testAutomationId: "searchInput", ref: this.inputRef, autoComplete: "off", value: value, name: name, placeholder: textSearchPlaceholder, onChange: this.handleChange, onKeyDown: this.handleEnter, "aria-label": textSearchPlaceholder }),
            button));
    };
    Search.prototype.renderResults = function () {
        var _a = this.props, value = _a.value, textShowAllResults = _a.textShowAllResults, textNoResults = _a.textNoResults;
        var _b = this.state, focused = _b.focused, results = _b.results, initial = _b.initial;
        this.resultRefs = [];
        if (!focused || !value || !results || (!results.length && initial)) {
            return null;
        }
        var content = !results.length ? (react_1.default.createElement("div", { className: "rc-search__no-result", "data-test-automation-id": "searchNoResults" }, textNoResults)) : (react_1.default.createElement(react_1.default.Fragment, null,
            react_1.default.createElement("ul", { className: "rc-search__results-list", "data-test-automation-id": "searchResultsList" }, this.getResults().map(this.renderResult)),
            react_1.default.createElement(Button_1.Button, { ref: this.showAllRef, className: "rc-search__results-footer", onClick: this.handleFullSearch, testAutomationId: "searchShowAll" },
                textShowAllResults,
                " \"",
                value,
                "\"")));
        return (react_1.default.createElement("div", { className: "rc-search__results", "data-test-automation-id": "searchResults" }, content));
    };
    Search.prototype.render = function () {
        var testAutomationId = this.props.testAutomationId;
        return (react_1.default.createElement("div", { className: "rc-search", "data-test-automation-id": testAutomationId, onFocus: this.handleFocus, onBlur: this.handleBlur, onKeyDown: this.handleKeyboardNavigation },
            this.renderSearchInput(),
            this.renderResults()));
    };
    Search.propTypes = {
        value: prop_types_1.default.string,
        name: prop_types_1.default.string,
        inputDebounce: prop_types_1.default.number,
        renderResult: prop_types_1.default.func.isRequired,
        searchProvider: prop_types_1.default.func.isRequired,
        onChange: prop_types_1.default.func.isRequired,
        onSearch: prop_types_1.default.func.isRequired,
        resultAction: prop_types_1.default.func.isRequired,
        maxResults: prop_types_1.default.number,
        testAutomationId: prop_types_1.default.string,
        textSearchPlaceholder: prop_types_1.default.string,
        textNoResults: prop_types_1.default.string,
        textShowAllResults: prop_types_1.default.string,
        textSearchLabel: prop_types_1.default.string,
        textClearLabel: prop_types_1.default.string
    };
    Search.defaultProps = {
        value: null,
        name: null,
        inputDebounce: 500,
        maxResults: 3,
        get textSearchPlaceholder() {
            return index_en_US_1.default.SEARCH;
        },
        get textShowAllResults() {
            return index_en_US_1.default.FASTSEARCH_SHOW_ALL;
        },
        get textNoResults() {
            return index_en_US_1.default.FASTSEARCH_NO_RESULTS;
        },
        get textSearchLabel() {
            return index_en_US_1.default.SEARCH;
        },
        get textClearLabel() {
            return index_en_US_1.default.CLEAR;
        },
        testAutomationId: 'search'
    };
    return Search;
}(react_1.default.Component));
exports.Search = Search;
//# sourceMappingURL=Search.js.map