"use strict";
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 __spreadArrays = (this && this.__spreadArrays) || function () {
    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
    for (var r = Array(s), k = 0, i = 0; i < il; i++)
        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
            r[k] = a[j];
    return r;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AutocompleteFullscreen = void 0;
var react_1 = __importStar(require("react"));
var react_native_1 = require("react-native");
var free_solid_svg_icons_1 = require("@fortawesome/free-solid-svg-icons");
var react_native_fontawesome_1 = require("@fortawesome/react-native-fontawesome");
var _ = __importStar(require("lodash"));
var rxjs_1 = require("rxjs");
var operators_1 = require("rxjs/operators");
var styled_components_1 = require("styled-components");
var use_immer_1 = require("use-immer");
var native_1 = require("../Flex/native");
var native_2 = require("../LoaderIcon/native");
var Pressable_1 = require("../Pressable");
var RFValue_1 = require("../RFValue");
var TextNative_1 = require("../TextNative");
var AutocompleteFullscreen_style_1 = require("./AutocompleteFullscreen.style");
function treatmentResults(results) {
    var i = -1;
    return results.map(function (el) {
        if (el.disabled) {
            return { id: JSON.stringify(el), disabled: true, data: el };
        }
        i += 1;
        return { id: i, data: el };
    });
}
exports.AutocompleteFullscreen = react_1.default.forwardRef(function Autocomplete(_a, ref) {
    var _this = this;
    var renderInput = _a.renderInput, renderItemSelected = _a.renderItemSelected, title = _a.title, name = _a.name, onSelect = _a.onSelect, fetch = _a.fetch, show = _a.show, onClose = _a.onClose, value = _a.value, _b = _a.initialSelect, initialSelect = _b === void 0 ? [] : _b, _c = _a.multiSelection, multiSelection = _c === void 0 ? false : _c, _d = _a.cleanAfterSelect, cleanAfterSelect = _d === void 0 ? false : _d, initialValue = _a.initialValue, _e = _a.NotFoundComponent, NotFoundComponent = _e === void 0 ? NotFoundAutoCompleteComponent : _e, rest = __rest(_a, ["renderInput", "renderItemSelected", "title", "name", "onSelect", "fetch", "show", "onClose", "value", "initialSelect", "multiSelection", "cleanAfterSelect", "initialValue", "NotFoundComponent"]);
    var theme = styled_components_1.useTheme();
    var textInputRef = react_1.useRef(null);
    var _f = react_1.useState(treatmentResults(initialValue || [])), results = _f[0], setResults = _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(false), error = _j[0], setError = _j[1];
    var fadeAnim = react_1.useRef(new react_native_1.Animated.Value(0)).current;
    var _k = use_immer_1.useImmer(initialSelect), selected = _k[0], setSelected = _k[1];
    react_1.useImperativeHandle(ref, function () { return textInputRef.current; }, []);
    var _l = react_1.useState(false), focus = _l[0], setFocus = _l[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(textInputRef.current.value)
                .pipe(operators_1.takeUntil($destroy.current))
                .subscribe(function (response) {
                setError(false);
                var resultsP = treatmentResults(response);
                setResults(resultsP);
                setNotFound(!resultsP.length);
                setSearching(false);
            }, function (e) {
                setSearching(false);
                if (setError)
                    setError(true);
            });
            return [2];
        });
    }); };
    var handleInputChange = function (text) {
        if (debounce.current)
            debounce.current.cancel();
        setSearching(true);
        debounce.current = _.debounce(onChangeDebounced, 300);
        debounce.current(text);
    };
    var selectItem = react_1.useCallback(function selectItem(e) {
        if (!e.disabled) {
            if (multiSelection) {
                setSelected(function (draft) {
                    if (draft.findIndex(function (v) { return _.isEqual(v, e.data); }) === -1) {
                        return __spreadArrays(draft, [e.data]);
                    }
                    draft.splice(draft.findIndex(function (v) { return _.isEqual(v, e.data); }), 1);
                    return draft;
                });
            }
            else {
                onSelect(e.data);
                setResults(treatmentResults(initialValue || []));
                onClose();
                if (cleanAfterSelect)
                    textInputRef.current.value = '';
            }
        }
    }, []);
    function applySelect() {
        onSelect(selected);
        onClose();
    }
    react_1.useEffect(function () { return function () {
        clearInterval(closeAutocomplete.current);
    }; }, []);
    var renderRow = react_1.useCallback(function (item) {
        return (react_1.default.createElement(AutoCompleteItem, { item: item.item, checked: selected.findIndex(function (v) { return _.isEqual(v, item.item.data); }) !== -1, index: "" + item.item.id, selectItem: selectItem, renderInput: renderInput }));
    }, [renderInput, selected]);
    var renderItemSelect = react_1.useCallback(function (item) {
        return (react_1.default.createElement(AutoCompleteSelectItem, { item: item.item, index: "" + item.item.id, renderInput: renderItemSelected, selectItem: selectItem }));
    }, [renderItemSelected, selectItem]);
    function onRequestClose() {
        onClose();
    }
    return (react_1.default.createElement(react_native_1.Modal, { visible: show, animated: true, animationType: "slide", onRequestClose: onRequestClose },
        react_1.default.createElement(native_1.Flex, { flex: 1 },
            react_1.default.createElement(AutocompleteFullscreen_style_1.InputContainer, null,
                react_1.default.createElement(AutocompleteFullscreen_style_1.BtnBack, { onPress: function () { return onClose(); }, testID: "back-button" },
                    react_1.default.createElement(native_1.Flex, { flex: 1, alignItems: "center", horizontal: true },
                        react_1.default.createElement(AutocompleteFullscreen_style_1.IconSearch, { icon: free_solid_svg_icons_1.faArrowLeft, color: "white", size: 24 }))),
                react_1.default.createElement(native_1.Flex, { flex: 1 },
                    react_1.default.createElement(AutocompleteFullscreen_style_1.Input, { testID: "autocomplete#input", ref: textInputRef, placeholder: "Pesquisar", onChangeText: handleInputChange }))),
            !!selected.length && (react_1.default.createElement(native_1.Flex, { paddingVertical: 7 },
                react_1.default.createElement(react_native_1.FlatList, { horizontal: true, keyExtractor: keyExtractor, keyboardShouldPersistTaps: "always", showsHorizontalScrollIndicator: false, data: selected, renderItem: renderItemSelect }))),
            searching && (react_1.default.createElement(native_1.Flex, { flex: 1, justifyContent: "center", testID: "autocomplete#loading" },
                react_1.default.createElement(native_2.LoaderIcon, { size: 90, color: (theme === null || theme === void 0 ? void 0 : theme.primary) || 'black' }))),
            !searching && error && (react_1.default.createElement(AutocompleteFullscreen_style_1.ErrorContainer, { testID: "autocomplete#error" },
                react_1.default.createElement(AutocompleteFullscreen_style_1.ErrorContainerText, null, "Erro ao conectar com servidor, verifique sua conex\u00E3o!"))),
            multiSelection && (react_1.default.createElement(AutocompleteFullscreen_style_1.BtnCheck, { testID: "autocomplete#apply", onPress: applySelect },
                react_1.default.createElement(react_native_fontawesome_1.FontAwesomeIcon, { icon: free_solid_svg_icons_1.faCheck, color: "white", size: RFValue_1.RSValue(20) }))),
            notFound && !searching && react_1.default.createElement(NotFoundComponent, null),
            !searching && !error && (react_1.default.createElement(react_native_1.FlatList, { showsVerticalScrollIndicator: false, extraData: results, data: results, keyboardShouldPersistTaps: "always", keyExtractor: keyExtractor, renderItem: renderRow })))));
});
var NotFoundAutoCompleteComponent = function () {
    return react_1.default.createElement(TextNative_1.TextNative, { style: { padding: 10 } }, "Nenhum resultado encontrado");
};
function keyExtractor(item, index) {
    return "item-" + index;
}
var AutoCompleteItem = react_1.default.memo(function AutoCompleteItem(_a) {
    var item = _a.item, index = _a.index, selectItem = _a.selectItem, renderInput = _a.renderInput, checked = _a.checked;
    var onPress = function () {
        selectItem(item);
    };
    return item.disabled ? (react_1.default.createElement(react_native_1.View, { key: "item-" + index, testID: "item-" + index }, renderInput(item.data, checked))) : (react_1.default.createElement(Pressable_1.Pressable, { onPress: onPress, key: "item-" + index, testID: "item-" + index, ripple: true }, renderInput(item.data, checked)));
}, function (old, current) {
    return _.isEqual(old, current);
});
var AutoCompleteSelectItem = react_1.default.memo(function AutoCompleteSelectItem(_a) {
    var item = _a.item, index = _a.index, renderInput = _a.renderInput, selectItem = _a.selectItem;
    var onPress = function () {
        selectItem(item);
    };
    return (react_1.default.createElement(Pressable_1.Pressable, { key: "item-" + index, testID: "item-select-" + index, onPress: onPress }, renderInput(item)));
}, function (old, current) {
    return _.isEqual(old, current);
});
//# sourceMappingURL=AutocompleteFullscreen.js.map