"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 __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.SelectAutocomplete = exports.SelectAutocompletePure = 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 free_solid_svg_icons_1 = require("@fortawesome/free-solid-svg-icons");
var react_fontawesome_1 = require("@fortawesome/react-fontawesome");
var _ = __importStar(require("lodash"));
var rxjs_1 = require("rxjs");
var operators_1 = require("rxjs/operators");
var use_deep_compare_effect_1 = __importDefault(require("use-deep-compare-effect"));
var CloseBtn_1 = require("../CloseBtn");
var Input_1 = require("../Input");
var styles_1 = require("../styles");
var S = __importStar(require("./SelectAutocomplete.style"));
var SelectAutocompleteCore_1 = require("./SelectAutocompleteCore");
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.SelectAutocompletePure = react_1.default.forwardRef(function SelectAutocompletePure(_a, ref) {
    var _b, _c;
    var _d = _a.renderInput, renderInput = _d === void 0 ? function (item) { return react_1.default.createElement("div", null, item); } : _d, name = _a.name, onSelect = _a.onSelect, getAsyncLabel = _a.getAsyncLabel, fetch = _a.fetch, placeHolder = _a.placeHolder, setError = _a.setError, _e = _a.initialFetch, initialFetch = _e === void 0 ? [] : _e, options = _a.options, _f = _a.isClearable, isClearable = _f === void 0 ? false : _f, 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, rest = __rest(_a, ["renderInput", "name", "onSelect", "getAsyncLabel", "fetch", "placeHolder", "setError", "initialFetch", "options", "isClearable", "NotFoundComponent", "title", "prefix", "suffix", "textRight", "textCenter", "loading", "mask", "withoutDotNumber", "decimals", "error", "value", "onInput", "onEnter", "defaultValue"]);
    var inputProps = {
        title: title,
        prefix: prefix,
        suffix: suffix,
        textRight: textRight,
        textCenter: textCenter,
        loading: loading,
        mask: mask,
        withoutDotNumber: withoutDotNumber,
        decimals: decimals,
        error: error,
        onInput: onInput,
        onEnter: onEnter,
        defaultValue: defaultValue,
    };
    var textInput = react_1.useRef(null);
    var _g = react_1.useState(!options ? convertArrayFetchToOptions(initialFetch) : options.map(function (el, i) { return (__assign(__assign({}, el), { id: i })); })), result = _g[0], setResults = _g[1];
    var _h = react_1.useState(false), open = _h[0], setOpen = _h[1];
    use_deep_compare_effect_1.default(function () {
        setResults(!options ? convertArrayFetchToOptions(initialFetch) : options.map(function (el, i) { return (__assign(__assign({}, el), { id: i })); }));
    }, [initialFetch]);
    var _j = react_1.useState(false), searching = _j[0], setSearching = _j[1];
    var _k = react_1.useState(false), notFound = _k[0], setNotFound = _k[1];
    var _l = react_1.useState(0), position = _l[0], setPosition = _l[1];
    var _m = react_1.useState(0), lengthItems = _m[0], setLengthItems = _m[1];
    var _o = react_1.useState(''), selectedLabel = _o[0], setSelectedLabel = _o[1];
    var _p = react_1.useState(false), typing = _p[0], setTyping = _p[1];
    react_1.useImperativeHandle(ref, function () { return textInput.current; }, []);
    var debounce = react_1.useRef();
    var $destroy = react_1.useRef(new rxjs_1.Subject());
    var closeSelectAutocomplete = react_1.useRef();
    react_1.useEffect(function () { return function () { return debounce.current && debounce.current.cancel(); }; }, []);
    var NotFoundComponent = (NotFoundComponentCustom !== null && NotFoundComponentCustom !== void 0 ? NotFoundComponentCustom : NotFoundAutoCompleteComponent);
    function onChangeDebounced(text) {
        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;
        }
        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);
        });
    }
    function handleInputChange(text) {
        setTyping(textInput.current.value != '');
        if (debounce.current)
            debounce.current.cancel();
        setSearching(true);
        debounce.current = _.debounce(onChangeDebounced, 300);
        debounce.current(text);
        if (onInput)
            onInput(text);
    }
    function closeAutoComplete() {
        closeSelectAutocomplete.current = setInterval(function () { return setOpen(false); }, 200);
        textInput.current.value = '';
        setTyping(false);
        if (rest.onBlur)
            rest.onBlur();
    }
    function openAutoComplete() {
        textInput.current.focus();
        clearInterval(closeSelectAutocomplete.current);
        setOpen(true);
        if (rest.onFocus)
            rest.onFocus();
    }
    function clearInput() {
        if (onSelect)
            onSelect(null);
    }
    function selectItem(e) {
        textInput.current.blur();
        if (options)
            setResults(options.map(function (el, i) { return (__assign(__assign({}, el), { id: i })); }));
        if (!e.disabled) {
            if (onSelect)
                onSelect(e.value);
            setOpen(false);
        }
        textInput.current.value = '';
        setTyping(false);
    }
    react_1.useEffect(function () { return function () {
        clearInterval(closeSelectAutocomplete.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);
    });
    var label = value ? (_c = (_b = (options !== null && options !== void 0 ? options : result).find(function (i) { return _.isEqual(i.value, value); })) === null || _b === void 0 ? void 0 : _b.name) !== null && _c !== void 0 ? _c : '' : null;
    return (react_1.default.createElement(styles_1.FormStyle, __assign({ "data-cy": "autocomplete-" + name }, rest),
        react_1.default.createElement(S.Container, null,
            react_1.default.createElement(Input_1.Input, __assign({}, inputProps, { ref: textInput, onInput: handleInputChange, onFocus: openAutoComplete, onBlur: closeAutoComplete, loading: searching, "data-testid": "select-autocomplete--input", prefix: react_1.default.createElement(react_1.default.Fragment, null,
                    !typing && (react_1.default.createElement("div", { className: "text-selected", "data-testid": "text-selected-label" }, label)),
                    !typing && !label && placeHolder && react_1.default.createElement("div", { className: "place-holder" }, placeHolder)), suffix: react_1.default.createElement(react_1.default.Fragment, null,
                    label && isClearable && (react_1.default.createElement(CloseBtn_1.CloseBtn, { size: 13, color: "#444", onClick: clearInput, "data-testid": "select-autocomplete--clear" })),
                    react_1.default.createElement("span", { className: "line" }),
                    react_1.default.createElement("span", { onClick: openAutoComplete },
                        react_1.default.createElement("div", { className: "select-icon" },
                            react_1.default.createElement(react_fontawesome_1.FontAwesomeIcon, { icon: free_solid_svg_icons_1.faAngleDown })))) })),
            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); }, "data-testid": "select-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.SelectAutocomplete = react_1.default.forwardRef(function SelectAutocomplete(props, ref) {
    return react_1.default.createElement(SelectAutocompleteCore_1.SelectAutocompleteCore, __assign({}, props, { as: exports.SelectAutocompletePure, ref: ref }));
});
//# sourceMappingURL=SelectAutocomplete.js.map