"use strict";
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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    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) : adopt(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 __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Autocomplete = void 0;
var react_1 = __importStar(require("react"));
var _ = __importStar(require("lodash"));
var rxjs_1 = require("rxjs");
var operators_1 = require("rxjs/operators");
var useEventListener_1 = require("../../../hooks/useEventListener");
var web_1 = require("../../LoaderIcon/web");
var Autocomplete_style_1 = __importDefault(require("./Autocomplete.style"));
exports.Autocomplete = react_1.default.forwardRef(function Autocomplete(_a, ref) {
    var _this = this;
    var renderInput = _a.renderInput, title = _a.title, name = _a.name, select = _a.select, fetch = _a.fetch, prefix = _a.prefix, _b = _a.placeholder, placeholder = _b === void 0 ? 'Selecionar...' : _b, clearable = _a.clearable, valueSelected = _a.valueSelected, error = _a.error, value = _a.value, setError = _a.setError, _c = _a.cleanAfterSelect, cleanAfterSelect = _c === void 0 ? false : _c, _d = _a.NotFoundComponent, NotFoundComponent = _d === void 0 ? NotFoundAutoCompleteComponent : _d, rest = __rest(_a, ["renderInput", "title", "name", "select", "fetch", "prefix", "placeholder", "clearable", "valueSelected", "error", "value", "setError", "cleanAfterSelect", "NotFoundComponent"]);
    var textInput = react_1.useRef();
    var _e = react_1.useState([]), result = _e[0], setResults = _e[1];
    var _f = react_1.useState(false), open = _f[0], setOpen = _f[1];
    var _g = react_1.useState(false), searching = _g[0], setSearching = _g[1];
    var _h = react_1.useState(false), notFound = _h[0], setNotFound = _h[1];
    var _j = react_1.useState(0), position = _j[0], setPosition = _j[1];
    var _k = react_1.useState(0), lengthItems = _k[0], setLengthItems = _k[1];
    var _l = react_1.useState(false), haveText = _l[0], setHaveText = _l[1];
    react_1.useImperativeHandle(ref, function () { return textInput.current; }, []);
    var _m = react_1.useState(false), focus = _m[0], setFocus = _m[1];
    var debounce = react_1.useRef();
    var $destroy = react_1.useRef(new rxjs_1.Subject());
    var closeAutocomplete = react_1.useRef();
    var onChangeDebounced = function () { return __awaiter(_this, void 0, void 0, function () {
        return __generator(this, function (_a) {
            $destroy.current.next();
            fetch(textInput.current.value)
                .pipe(operators_1.takeUntil($destroy.current))
                .subscribe(function (results) {
                var i = -1;
                var resultsP = results.map(function (el) {
                    if (el.disabled) {
                        return { id: JSON.stringify(el), disabled: true, data: el };
                    }
                    i += 1;
                    return { id: i, data: el };
                });
                setPosition(0);
                setLengthItems(i + 1);
                setResults(resultsP);
                setOpen(true);
                setNotFound(i + 1 === 0);
                setSearching(false);
            }, function (e) {
                setSearching(false);
                if (setError)
                    setError(e);
            });
            return [2];
        });
    }); };
    react_1.useEffect(function () { return function () {
        clearInterval(closeAutocomplete.current);
    }; }, []);
    var handleInputChange = function (e) {
        if (debounce.current)
            debounce.current.cancel();
        setSearching(true);
        debounce.current = _.debounce(onChangeDebounced, 300);
        debounce.current(e.target.value);
    };
    function closeAutoComplete() {
        setFocus(false);
        closeAutocomplete.current = setInterval(function () { return setOpen(false); }, 200);
        setHaveText(false);
        if (cleanAfterSelect)
            textInput.current.value = '';
        if (rest.onBlur)
            rest.onBlur();
    }
    function openAutoComplete() {
        setFocus(true);
        clearInterval(closeAutocomplete.current);
        setOpen(true);
        if (rest.onFocus)
            rest.onFocus();
    }
    function selectItem(e) {
        if (!(e === null || e === void 0 ? void 0 : e.disabled)) {
            select(e);
            setOpen(false);
            setHaveText(false);
            textInput.current.blur();
        }
    }
    function onInput(ev) {
        setHaveText(ev.currentTarget.value.length !== 0);
    }
    function onClear() {
        selectItem(null);
    }
    useEventListener_1.useEventListener('keydown.arrowdown', function (event) {
        if (open) {
            var nextPos = position + 1;
            if (nextPos >= lengthItems) {
                nextPos = 0;
            }
            setPosition(nextPos);
        }
    });
    useEventListener_1.useEventListener('keydown.arrowup', function (event) {
        if (open) {
            var nextPos = position - 1;
            if (nextPos < 0) {
                nextPos = lengthItems - 1;
                if (lengthItems - 1 < 0) {
                    nextPos = 0;
                }
            }
            setPosition(nextPos);
        }
    });
    useEventListener_1.useEventListener('keydown.enter', function (event) {
        var item = result.find(function (e) { return e.id === position; });
        if (item)
            selectItem(item.data);
    });
    return (react_1.default.createElement(Autocomplete_style_1.default, { "data-cy": "autocomplete-" + name },
        react_1.default.createElement("div", { className: "input-title " + (focus && 'focus') }, title),
        react_1.default.createElement("div", { className: "input-border " + (error && 'has-error') + " " + (focus && 'focus') },
            prefix && react_1.default.createElement("div", { className: "prefix" }, prefix),
            react_1.default.createElement("div", { className: "input-container--inner" },
                react_1.default.createElement("input", __assign({}, rest, { placeholder: valueSelected ? '' : placeholder, ref: textInput, onChange: handleInputChange, onFocus: openAutoComplete, onBlur: closeAutoComplete, onInput: onInput, "data-testid": "autocomplete--input" })),
                !haveText && (react_1.default.createElement("div", { className: "text-placeholder", "data-testid": "autocomplete--text-placeholder" }, valueSelected))),
            react_1.default.createElement("div", { className: "suffix" }, searching && react_1.default.createElement(web_1.LoaderIcon, { size: 24 })),
            clearable && !!valueSelected && (react_1.default.createElement("div", { className: "suffix clearable", onClick: onClear },
                react_1.default.createElement("svg", { height: "20", width: "20", viewBox: "0 0 20 20", "aria-hidden": "true", focusable: "false", className: "css-6q0nyr-Svg" },
                    react_1.default.createElement("path", { d: "M14.348 14.849c-0.469 0.469-1.229 0.469-1.697 0l-2.651-3.030-2.651 3.029c-0.469 0.469-1.229 0.469-1.697 0-0.469-0.469-0.469-1.229 0-1.697l2.758-3.15-2.759-3.152c-0.469-0.469-0.469-1.228 0-1.697s1.228-0.469 1.697 0l2.652 3.031 2.651-3.031c0.469-0.469 1.228-0.469 1.697 0s0.469 1.229 0 1.697l-2.758 3.152 2.758 3.15c0.469 0.469 0.469 1.229 0 1.698z" })))),
            react_1.default.createElement("span", { className: "line" }),
            react_1.default.createElement("div", { className: "suffix down-icon" },
                react_1.default.createElement("svg", { height: "20", width: "20", viewBox: "0 0 20 20", "aria-hidden": "true", focusable: "false", className: "css-6q0nyr-Svg" },
                    react_1.default.createElement("path", { d: "M4.516 7.548c0.436-0.446 1.043-0.481 1.576 0l3.908 3.747 3.908-3.747c0.533-0.481 1.141-0.446 1.574 0 0.436 0.445 0.408 1.197 0 1.615-0.406 0.418-4.695 4.502-4.695 4.502-0.217 0.223-0.502 0.335-0.787 0.335s-0.57-0.112-0.789-0.335c0 0-4.287-4.084-4.695-4.502s-0.436-1.17 0-1.615z" })))),
        open && (react_1.default.createElement("ul", { className: "autocomplete-list", "data-testid": "autocomplete-list" },
            result.map(function (e, i) { return (react_1.default.createElement("li", { key: e.id, onMouseDown: function () { return selectItem(e.data); }, "data-testid": "autocomplete-list--row-" + i, className: (position === e.id && 'active') + " " + (!!e.disabled && 'disabled') }, renderInput(e.data))); }),
            notFound && react_1.default.createElement(NotFoundComponent, null)))));
});
var NotFoundAutoCompleteComponent = function () {
    return react_1.default.createElement(react_1.default.Fragment, null, "N\u00E3o encontrado");
};
//# sourceMappingURL=Autocomplete.js.map