"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.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 (_) 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 = exports.AutocompletePure = void 0;
var react_1 = __importStar(require("react"));
var react_hooks_1 = require("@devesharp/react-hooks");
var react_utils_1 = require("@devesharp/react-utils");
var _ = __importStar(require("lodash"));
var rxjs_1 = require("rxjs");
var operators_1 = require("rxjs/operators");
var Input_1 = require("../Input");
var styles_1 = require("../styles");
var Autocomplete_style_1 = __importDefault(require("./Autocomplete.style"));
var AutocompleteCore_1 = require("./AutocompleteCore");
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 = react_1.default.forwardRef(function AutocompletePure(_a, ref) {
    var _this = this;
    var _b = _a.renderInput, renderInput = _b === void 0 ? function (item) { return react_1.default.createElement("div", null, item); } : _b, name = _a.name, onSelect = _a.onSelect, fetch = _a.fetch, setError = _a.setError, _c = _a.cleanAfterSelect, cleanAfterSelect = _c === void 0 ? false : _c, NotFoundComponentCustom = _a.NotFoundComponent, title = _a.title, prefix = _a.prefix, suffix = _a.suffix, textRight = _a.textRight, textCenter = _a.textCenter, loading = _a.loading, mask = _a.mask, withoutDotNumber = _a.withoutDotNumber, decimals = _a.decimals, error = _a.error, value = _a.value, onInput = _a.onInput, onEnter = _a.onEnter, defaultValue = _a.defaultValue, options = _a.options, rest = __rest(_a, ["renderInput", "name", "onSelect", "fetch", "setError", "cleanAfterSelect", "NotFoundComponent", "title", "prefix", "suffix", "textRight", "textCenter", "loading", "mask", "withoutDotNumber", "decimals", "error", "value", "onInput", "onEnter", "defaultValue", "options"]);
    var inputProps = {
        title: title,
        prefix: prefix,
        suffix: suffix,
        textRight: textRight,
        textCenter: textCenter,
        loading: loading,
        mask: mask,
        withoutDotNumber: withoutDotNumber,
        decimals: decimals,
        error: error,
        value: value,
        onInput: onInput,
        onEnter: onEnter,
        defaultValue: defaultValue,
    };
    var textInput = react_1.useRef(null);
    var _d = react_1.useState([]), result = _d[0], setResults = _d[1];
    var _e = react_1.useState(false), open = _e[0], setOpen = _e[1];
    var _f = react_1.useState(false), searching = _f[0], setSearching = _f[1];
    var _g = react_1.useState(false), notFound = _g[0], setNotFound = _g[1];
    var _h = react_1.useState(0), position = _h[0], setPosition = _h[1];
    var _j = react_1.useState(0), lengthItems = _j[0], setLengthItems = _j[1];
    react_1.useImperativeHandle(ref, function () { return textInput.current; }, []);
    var debounce = react_1.useRef();
    var $destroy = react_1.useRef(new rxjs_1.Subject());
    var closeAutocomplete = react_1.useRef();
    var NotFoundComponent = (NotFoundComponentCustom !== null && NotFoundComponentCustom !== void 0 ? NotFoundComponentCustom : NotFoundAutoCompleteComponent);
    var onChangeDebounced = function (text) { return __awaiter(_this, void 0, void 0, function () {
        return __generator(this, function (_a) {
            if (options) {
                setPosition(0);
                setLengthItems(options.length);
                setResults(options
                    .filter(function (i) { return react_utils_1.NormalizeString(i.name).includes(react_utils_1.NormalizeString(text)); })
                    .map(function (el, i) { return (__assign(__assign({}, el), { id: i })); }));
                setOpen(true);
                setSearching(false);
                return [2];
            }
            fetch(text)
                .pipe(operators_1.takeUntil($destroy.current))
                .subscribe(function (results) {
                setPosition(0);
                var items = convertArrayFetchToOptions(results);
                setLengthItems(items.filter(function (i) { return !i.disabled; }).length);
                setResults(items);
                setOpen(true);
                setNotFound(items.filter(function (i) { return !i.disabled; }).length === 0);
                setSearching(false);
            }, function (e) {
                setSearching(false);
                if (setError)
                    setError(e);
            });
            return [2];
        });
    }); };
    var handleInputChange = function (text) {
        if (debounce.current)
            debounce.current.cancel();
        setSearching(true);
        debounce.current = _.debounce(onChangeDebounced, 300);
        debounce.current(text);
        if (onInput)
            onInput(text);
    };
    function closeAutoComplete() {
        closeAutocomplete.current = setInterval(function () { return setOpen(false); }, 200);
        if (rest.onBlur)
            rest.onBlur();
    }
    function openAutoComplete() {
        clearInterval(closeAutocomplete.current);
        setOpen(true);
        if (rest.onFocus)
            rest.onFocus();
    }
    function selectItem(e) {
        if (!e.disabled) {
            if (onSelect)
                onSelect(e.name, e);
            textInput.current.value = e.name;
            if (onInput)
                onInput(e.name);
            setResults([]);
            setOpen(false);
            if (cleanAfterSelect) {
                textInput.current.value = '';
                if (onInput)
                    onInput('');
            }
        }
    }
    react_1.useEffect(function () { return function () {
        clearInterval(closeAutocomplete.current);
    }; }, []);
    react_hooks_1.useEventListener('keydown.arrowdown', function (event) {
        if (open) {
            var nextPos = position + 1;
            if (nextPos >= lengthItems) {
                nextPos = 0;
            }
            setPosition(nextPos);
        }
    });
    react_hooks_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);
        }
    });
    react_hooks_1.useEventListener('keydown.enter', function (event) {
        var item = result.find(function (e) { return e.id === position; });
        if (item)
            selectItem(item);
    });
    return (react_1.default.createElement(styles_1.FormStyle, __assign({ "data-cy": "autocomplete-" + name }, rest),
        react_1.default.createElement(Autocomplete_style_1.default, null,
            react_1.default.createElement(Input_1.Input, __assign({}, inputProps, { ref: textInput, onInput: handleInputChange, onFocus: openAutoComplete, onBlur: closeAutoComplete, loading: searching, "data-testid": "autocomplete--input" })),
            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, onClick: function () { return selectItem(e); }, onMouseOver: function () { return !e.disabled && setPosition(e.id); }, "data-testid": "autocomplete-list--row-" + i, className: (position === e.id && 'active') + " " + (!!e.disabled && 'disabled') }, renderInput(e.name, e.value))); }),
                notFound && react_1.default.createElement(NotFoundComponent, null))))));
});
var NotFoundAutoCompleteComponent = function () {
    return react_1.default.createElement(react_1.default.Fragment, null, "N\u00E3o encontrado");
};
exports.Autocomplete = react_1.default.forwardRef(function Autocomplete(props, ref) {
    return react_1.default.createElement(AutocompleteCore_1.AutocompleteCore, __assign({}, props, { as: exports.AutocompletePure, ref: ref }));
});
//# sourceMappingURL=Autocomplete.js.map