"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;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (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.prototype.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 (g && (g = 0, op[0] && (_ = 0)), _) 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.AutocompletePure = void 0;
var react_1 = __importStar(require("react"));
var useClickOutside_1 = require("@devesharp/react-hooks/lib/useClickOutside");
var useDeepEffect_1 = require("@devesharp/react-hooks/lib/useDeepEffect");
var useEventListener_1 = require("@devesharp/react-hooks/lib/useEventListener");
var Utils_1 = require("@devesharp/react-utils/lib/Utils");
var debounce_1 = __importDefault(require("lodash/debounce"));
var rxjs_1 = require("rxjs");
var takeUntil_1 = require("rxjs/internal/operators/takeUntil");
var styles_1 = require("../styles");
var AutocompletePure_style_1 = __importDefault(require("./AutocompletePure.style"));
function convertArrayFetchToOptions(results) {
    var i = -1;
    return results.map(function (el) {
        var _a, _b;
        if (el.disabled) {
            return {
                id: (_a = el.id) !== null && _a !== void 0 ? _a : JSON.stringify(el),
                disabled: true,
                value: (_b = el.value) !== null && _b !== void 0 ? _b : el.name,
                name: el.name,
            };
        }
        i += 1;
        return { id: i, value: el.value, name: el.name };
    });
}
exports.AutocompletePure = (0, react_1.forwardRef)(function AutocompletePure(_a, ref) {
    var _this = this;
    var _b = _a.renderRow, renderRow = _b === void 0 ? function (item, value, active, disabled) { return (react_1.default.createElement(RenderRow, { item: item, active: active, disabled: disabled })); } : _b, onSelect = _a.onSelect, fetchItems = _a.fetchItems, initialSearch = _a.initialSearch, itemsDefault = _a.items, setError = _a.setError, _c = _a.cleanItemsAfterSelect, cleanItemsAfterSelect = _c === void 0 ? false : _c, _d = _a.persistOpenAutoCompleteItemsAfterSelect, persistOpenAutoCompleteItemsAfterSelect = _d === void 0 ? false : _d, _e = _a.NotFoundComponent, NotFoundComponent = _e === void 0 ? NotFoundAutoCompleteComponent : _e, As = _a.as, rest = __rest(_a, ["renderRow", "onSelect", "fetchItems", "initialSearch", "items", "setError", "cleanItemsAfterSelect", "persistOpenAutoCompleteItemsAfterSelect", "NotFoundComponent", "as"]);
    var refAs = (0, react_1.useRef)(null);
    (0, react_1.useImperativeHandle)(ref, function () { return ({
        onForceSearch: function (text, showAutoComplete) {
            if (showAutoComplete === void 0) { showAutoComplete = false; }
            searchText(text, !showAutoComplete);
        },
    }); }, [searchText]);
    var autocompleteRef = (0, react_1.useRef)();
    var scrollAutoComplete = (0, react_1.useRef)(null);
    var _f = (0, react_1.useState)([]), items = _f[0], setItems = _f[1];
    var _g = (0, react_1.useState)(false), open = _g[0], setOpen = _g[1];
    var _h = (0, react_1.useState)(false), searching = _h[0], setSearching = _h[1];
    var _j = (0, react_1.useState)(false), notFound = _j[0], setNotFound = _j[1];
    var _k = (0, react_1.useState)(0), position = _k[0], setPosition = _k[1];
    var _l = (0, react_1.useState)(0), lengthItems = _l[0], setLengthItems = _l[1];
    var debounce = (0, react_1.useRef)();
    var $destroy = (0, react_1.useRef)(new rxjs_1.Subject());
    var closeAutocomplete = (0, react_1.useRef)();
    var onChangeDebounced = function (text, notShowAutoComplete) {
        if (notShowAutoComplete === void 0) { notShowAutoComplete = false; }
        return __awaiter(_this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                if (itemsDefault) {
                    setPosition(0);
                    setLengthItems(itemsDefault.length);
                    setItems(itemsDefault
                        .filter(function (i) { return (0, Utils_1.NormalizeString)(i.name).includes((0, Utils_1.NormalizeString)(text)); })
                        .map(function (el, i) { return (__assign(__assign({}, el), { id: i })); }));
                    setOpen(true);
                    setSearching(false);
                    return [2];
                }
                $destroy.current.next();
                searchText(text, notShowAutoComplete);
                return [2];
            });
        });
    };
    function searchText(text, notShowAutoComplete) {
        if (notShowAutoComplete === void 0) { notShowAutoComplete = false; }
        setSearching(true);
        fetchItems(text)
            .pipe((0, takeUntil_1.takeUntil)($destroy.current))
            .subscribe(function (results) {
            setPosition(0);
            var itemsFetch = convertArrayFetchToOptions(results);
            setLengthItems(itemsFetch.filter(function (i) { return !i.disabled; }).length);
            setItems(itemsFetch);
            if (!notShowAutoComplete)
                setOpen(true);
            setNotFound(itemsFetch.length === 0);
            setSearching(false);
        }, function (e) {
            setSearching(false);
            if (setError)
                setError(e);
        });
    }
    function handleInputChange(text) {
        if (debounce.current)
            debounce.current.cancel();
        setSearching(true);
        debounce.current = (0, debounce_1.default)(onChangeDebounced, 300);
        debounce.current(text);
    }
    function closeAutoComplete() {
        $destroy.current.next();
        closeAutocomplete.current = setTimeout(function () { return setOpen(false); }, 200);
    }
    function openAutoComplete() {
        clearInterval(closeAutocomplete.current);
        setOpen(true);
    }
    function selectItem(item) {
        var _a;
        if (!item.disabled) {
            if (!persistOpenAutoCompleteItemsAfterSelect)
                setOpen(false);
            (_a = refAs.current) === null || _a === void 0 ? void 0 : _a.onSelect(item);
            if (onSelect)
                onSelect(item.name, item);
            if (cleanItemsAfterSelect)
                setItems([]);
        }
    }
    (0, react_1.useEffect)(function () {
        if (initialSearch != null) {
            onChangeDebounced(initialSearch, true);
        }
    }, []);
    (0, useDeepEffect_1.useDeepEffect)(function () {
        if (initialSearch != null) {
            onChangeDebounced(initialSearch, true);
        }
    }, [fetchItems]);
    (0, react_1.useEffect)(function () { return function () {
        clearInterval(closeAutocomplete.current);
    }; }, []);
    (0, useEventListener_1.useEventListener)('keydown.esc', function () {
        if (open) {
            setOpen(false);
        }
    });
    (0, useEventListener_1.useEventListener)('keydown.arrowdown', function () {
        if (open) {
            var nextPos = position + 1;
            var index = items.findIndex(function (e) { return e.id === position; }) + 1;
            if (nextPos >= lengthItems) {
                nextPos = 0;
                index = 0;
            }
            if (Array.from(scrollAutoComplete.current.getElementsByTagName('li'))[0]) {
                var itemSize = Array.from(scrollAutoComplete.current.getElementsByTagName('li'))[0].getBoundingClientRect().height;
                var heightScroll = scrollAutoComplete.current.getBoundingClientRect().height;
                var heightScrollTop = scrollAutoComplete.current.scrollTop;
                if (!(heightScrollTop < itemSize * index && heightScrollTop + heightScroll > itemSize * index)) {
                    scrollAutoComplete.current.scrollTop = itemSize * (index + 1) - heightScroll;
                }
                setPosition(nextPos);
            }
        }
    });
    (0, useEventListener_1.useEventListener)('keydown.arrowup', function () {
        if (open) {
            var nextPos = position - 1;
            var index = items.findIndex(function (e) { return e.id === position; }) - 1;
            if (nextPos < 0) {
                nextPos = lengthItems - 1;
                index = lengthItems - 1;
                if (lengthItems - 1 < 0) {
                    nextPos = 0;
                    index = 0;
                }
            }
            if (Array.from(scrollAutoComplete.current.getElementsByTagName('li'))[0]) {
                var itemSize = Array.from(scrollAutoComplete.current.getElementsByTagName('li'))[0].getBoundingClientRect().height;
                var heightScroll = scrollAutoComplete.current.getBoundingClientRect().height;
                var heightScrollTop = scrollAutoComplete.current.scrollTop;
                if (!(heightScrollTop < itemSize * index && heightScrollTop + heightScroll > itemSize * index)) {
                    scrollAutoComplete.current.scrollTop = itemSize * index;
                }
                setPosition(nextPos);
            }
        }
    });
    (0, useEventListener_1.useEventListener)('keydown.enter', function () {
        if (open) {
            var item = items.find(function (e) { return e.id === position; });
            if (item)
                selectItem(item);
        }
    });
    (0, useClickOutside_1.useClickOutside)(function () {
        closeAutoComplete();
    }, autocompleteRef);
    return (react_1.default.createElement(styles_1.FormStyle, { ref: autocompleteRef, "data-testid": "autocomplete", className: "autocomplete-container" },
        react_1.default.createElement(AutocompletePure_style_1.default, null,
            react_1.default.createElement(As, __assign({}, rest, { ref: refAs, _handleInputChange: handleInputChange, _openAutoComplete: openAutoComplete, _closeAutoComplete: closeAutoComplete, _loading: searching })),
            open && (react_1.default.createElement("ul", { className: "autocomplete-list", "data-testid": "autocomplete-list", ref: scrollAutoComplete },
                items.map(function (item, i) { return (react_1.default.createElement("li", { key: "".concat(item.id), onClick: function () { return selectItem(item); }, onMouseOver: function () { return !item.disabled && setPosition(item.id); }, onFocus: function () { return !item.disabled && setPosition(item.id); }, "data-testid": "autocomplete-list--row-".concat(i), className: "".concat(position === item.id && 'active', " ").concat(!!item.disabled && 'disabled') }, renderRow(item.name, item.value, position === item.id, item.disabled))); }),
                notFound && react_1.default.createElement(NotFoundComponent, null))))));
});
function RenderRow(_a) {
    var item = _a.item, disabled = _a.disabled, active = _a.active;
    return react_1.default.createElement("div", { className: "item-row-autocomplete ".concat(disabled && 'disabled', " ").concat(active && 'active') }, item);
}
function NotFoundAutoCompleteComponent() {
    return react_1.default.createElement(react_1.default.Fragment, null, "N\u00E3o encontrado");
}
//# sourceMappingURL=AutocompletePure.js.map