"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 __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;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useViewList = void 0;
var react_1 = require("react");
var queryStringHelper = __importStar(require("query-string"));
var operators_1 = require("rxjs/operators");
var use_immer_1 = require("use-immer");
var AppContext_1 = __importDefault(require("../../components1/AppProvider/AppContext"));
var services_1 = require("../../services");
var useDidUpdateDeepCompareEffect_1 = require("../useDidUpdateDeepCompareEffect");
var useDidUpdateDeepCompareLayoutEffect_1 = require("../useDidUpdateDeepCompareLayoutEffect");
var useListener_1 = require("../useListener");
var useQueryString_1 = require("../useQueryString/useQueryString");
var useStateRef_1 = require("../useStateRef");
var useView_1 = require("../useView");
function useViewList(_a) {
    var _b = _a.filtersDefault, filtersDefaultOriginal = _b === void 0 ? {} : _b, _c = _a.limit, limit = _c === void 0 ? 20 : _c, _d = _a.infiniteScroll, infiniteScroll = _d === void 0 ? false : _d, _e = _a.disableQueryChange, disableQueryChange = _e === void 0 ? false : _e, _f = _a.ignoreFiltersInQuery, ignoreFiltersInQuery = _f === void 0 ? [] : _f, _g = _a.ignoreQueryInFilters, ignoreQueryInFilters = _g === void 0 ? [] : _g, _h = _a.reverseItems, reverseItems = _h === void 0 ? false : _h, _j = _a.resolves, resolves = _j === void 0 ? {} : _j, _k = _a.firstLoad, firstLoad = _k === void 0 ? true : _k, _l = _a.changeOnlyPath, changeOnlyPath = _l === void 0 ? null : _l, _m = _a.handleRequestBody, handleRequestBodyInitial = _m === void 0 ? function (filter) { return filter; } : _m, _o = _a.handleFilterToQuery, handleFilterToQueryInitial = _o === void 0 ? function (filter) { return filter; } : _o, _p = _a.handleQueryToFilter, handleQueryToFilterInitial = _p === void 0 ? function (filter) { return filter; } : _p;
    var _q = useView_1.useView({ resolves: resolves, firstLoad: firstLoad }), statusInfo = _q.statusInfo, setStatusInfo = _q.setStatusInfo, registerOnInit = _q.registerOnInit, registerOnInitError = _q.registerOnInitError, getParamsResolve = _q.getParamsResolve, registerResolveParams = _q.registerResolveParams, $destroy = _q.$destroy, reloadPage = _q.reloadPage;
    var history = react_1.useContext(AppContext_1.default).history;
    var skeletonResources = react_1.useRef(services_1.CreateRange(limit)).current;
    var _r = useStateRef_1.useStateRef(filtersDefaultOriginal), filtersDefault = _r[0], setFiltersDefault = _r[1];
    react_1.useEffect(function () {
        setFiltersDefault(filtersDefaultOriginal);
    }, [filtersDefaultOriginal]);
    var _s = use_immer_1.useImmer([]), resources = _s[0], setResources = _s[1];
    var _t = react_1.useState(0), resourcesTotal = _t[0], setResourceTotal = _t[1];
    react_1.useLayoutEffect(function () {
        setStatusInfo({
            searchingMore: false,
            searching: true,
            lastPage: false,
            errorLoadMore: false,
        });
    }, []);
    var _u = useStateRef_1.useStateRef(handleRequestBodyInitial), handleRequestBody = _u[0], setHandleRequestBody = _u[1];
    var _v = useStateRef_1.useStateRef(handleFilterToQueryInitial), handleFilterToQuery = _v[0], setHandleFilterToQuery = _v[1];
    var _w = useStateRef_1.useStateRef(handleQueryToFilterInitial), handleQueryToFilter = _w[0], setHandleQueryToFilter = _w[1];
    var queryString = useQueryString_1.useQueryString(changeOnlyPath);
    var _x = use_immer_1.useImmer(services_1.objectExcept(__assign(__assign({}, filtersDefault.current), handleQueryToFilter.current(queryString)), ignoreQueryInFilters)), filters = _x[0], __setFilters__ = _x[1];
    var _y = use_immer_1.useImmer({}), filtersOptions = _y[0], setFiltersOptions = _y[1];
    var setFilters = function setFilters(f, options) {
        if (options === void 0) { options = {}; }
        setFiltersOptions(function () { return options; });
        __setFilters__(function (draft) {
            var newDraft = f(draft);
            if (newDraft === undefined || newDraft === null) {
                draft = services_1.deleteEmpty(__assign(__assign({}, filtersDefault.current), draft));
            }
            else {
                return services_1.deleteEmpty(__assign(__assign({}, filtersDefault.current), newDraft));
            }
        });
    };
    react_1.useLayoutEffect(function () {
        registerResolveParams('items', function () { return handleRequestBody.current(__assign(__assign({}, filtersDefault.current), filters)); });
    }, []);
    var _z = useListener_1.useListener(), registerOnSearch = _z[0], callOnSearch = _z[1];
    react_1.useLayoutEffect(function () {
        registerOnInit(function (res) {
            if (res.items) {
                var items_1 = res.items;
                if (limit > items_1.count || items_1.count === 0) {
                    setStatusInfo({
                        lastPage: true,
                    });
                }
                setResources(function (draft) { return (!reverseItems ? items_1.results : Array.from(items_1.results).reverse()); });
                setResourceTotal(items_1.count);
            }
            setStatusInfo({
                searching: false,
            });
        });
    }, []);
    react_1.useLayoutEffect(function () {
        registerOnInitError(function () {
            setStatusInfo({
                searching: false,
            });
        });
    }, []);
    useDidUpdateDeepCompareLayoutEffect_1.useDidUpdateDeepCompareLayoutEffect(function () {
        if (!disableQueryChange && !filtersOptions.disableQueryChange) {
            var searchString = "?" + queryStringHelper.stringify(services_1.deleteEmpty(services_1.objectExcept(handleFilterToQuery.current(__assign(__assign({}, filtersDefault.current), filters)), ignoreFiltersInQuery)));
            var searchStringDefault = "?" + queryStringHelper.stringify(services_1.objectExcept(filtersDefault.current, ignoreFiltersInQuery));
            if (searchString === searchStringDefault) {
                searchString = '';
            }
            if (typeof document !== 'undefined') {
                if (window.location.search != searchString) {
                    if (filtersOptions.replaceUrl) {
                        if (!history) {
                            window.location.replace(searchString);
                        }
                        else {
                            history.replace({
                                search: searchString,
                            });
                        }
                    }
                    else if (!history) {
                        window.location.search = searchString;
                    }
                    else {
                        history.push({
                            search: searchString,
                        });
                    }
                }
            }
        }
        var resetResources = (!filters.page || filters.page <= 1) && (!filters.offset || filters.offset == 0);
        if (!filtersOptions.noRequest) {
            callOnSearch();
            loadResources({
                push: infiniteScroll,
                reset: resetResources,
            });
        }
        setFiltersOptions(function () { return ({}); });
    }, [filters]);
    useDidUpdateDeepCompareEffect_1.useDidUpdateDeepCompareEffect(function () {
        setFilters(function () { return services_1.objectExcept(handleQueryToFilter.current(queryString), ignoreQueryInFilters); }, {
            disableQueryChange: true,
        });
    }, [queryString]);
    function loadResources(options) {
        if (options === void 0) { options = {}; }
        if (resolves && resolves.items) {
            if (options.push && !options.reset) {
                setStatusInfo({
                    errorLoadMore: false,
                    errorLoadData: false,
                    searchingMore: true,
                });
            }
            else {
                setStatusInfo({
                    errorLoadMore: false,
                    errorLoadData: false,
                    searching: true,
                });
            }
            $destroy.next();
            resolves
                .items(handleRequestBody.current(__assign(__assign({}, filtersDefault.current), filters)))
                .pipe(operators_1.takeUntil($destroy))
                .subscribe(function (response) {
                var _a;
                var lastPage = false;
                if (!options.push || options.reset) {
                    setResources(function () { return (!reverseItems ? response.results : response.results.reverse()); });
                    setResourceTotal(response.count);
                    if (((_a = filters === null || filters === void 0 ? void 0 : filters.offset) !== null && _a !== void 0 ? _a : 0) + response.results.length >= response.count ||
                        response.results.length === 0) {
                        lastPage = true;
                    }
                }
                else {
                    setResources(function (draft) {
                        return reverseItems ? __spreadArrays(response.results.reverse(), draft) : __spreadArrays(draft, response.results);
                    });
                    setResourceTotal(response.count);
                    if (resources.length + response.results.length >= response.count ||
                        response.results.length === 0) {
                        lastPage = true;
                    }
                }
                setStatusInfo({
                    errorLoadData: false,
                    errorLoadMore: false,
                    searching: false,
                    searchingMore: false,
                    lastPage: lastPage,
                });
            }, function () {
                if (options.push) {
                    setStatusInfo({
                        errorLoadMore: true,
                        searchingMore: false,
                    });
                    setFilters(function (draft) {
                        var offset = draft.offset - limit;
                        return __assign(__assign({}, draft), { offset: offset > 0 ? 0 : offset });
                    }, {
                        noRequest: true,
                        disableQueryChange: true,
                    });
                }
                else {
                    setStatusInfo({
                        errorLoadData: true,
                        searching: false,
                    });
                }
            });
        }
    }
    function removeResource(id, softDelete) {
        if (softDelete === void 0) { softDelete = false; }
        setResources(function (items) {
            var index = items.findIndex(function (i) { return i.id === id; });
            if (index !== -1) {
                if (softDelete) {
                    items[index].deleted = true;
                }
                else {
                    items.splice(index, 1);
                }
                setResourceTotal(resourcesTotal - 1);
            }
        });
    }
    function removeManyResources(ids, softDelete) {
        if (softDelete === void 0) { softDelete = false; }
        var deletedItems = 0;
        setResources(function (items) {
            ids.forEach(function (id) {
                var index = items.findIndex(function (i) { return i.id === id; });
                if (index !== -1) {
                    if (softDelete) {
                        items[index].deleted = true;
                    }
                    else {
                        items.splice(index, 1);
                    }
                    deletedItems += 1;
                }
            });
            setResourceTotal(resourcesTotal - deletedItems);
        });
    }
    var setPage = react_1.useCallback(function setPage(page, options) {
        if (page < 1)
            page = 1;
        setFilters(function (draft) { return (__assign(__assign({}, draft), { page: null, offset: (page - 1) * limit })); }, options);
    }, [filters]);
    var setOffset = react_1.useCallback(function setOffset(offset, options) {
        setFilters(function (draft) { return (__assign(__assign({}, draft), { page: null, offset: offset })); }, options);
    }, [filters]);
    var setSort = react_1.useCallback(function setSort(sort, options) {
        setFilters(function (draft) { return (__assign(__assign({}, draft), { page: null, offset: 0, sort: sort })); }, options);
    }, [filters]);
    var loadNextPage = react_1.useCallback(function loadNextPage(options) {
        setFilters(function (draft) { return (__assign(__assign({}, draft), { offset: draft.offset ? draft.offset + limit : limit })); }, options);
    }, [filters]);
    var reloadResources = react_1.useCallback(function reloadResources(wait1s, options) {
        if (wait1s === void 0) { wait1s = true; }
        loadResources({ reset: true });
    }, [filters, resolves]);
    var resetPageViewList = react_1.useCallback(function resetPageViewList(wait1s, options) {
        if (wait1s === void 0) { wait1s = true; }
        setFilters(function () { return ({}); }, {
            noRequest: true,
        });
        if (history && !disableQueryChange) {
            history.push({
                search: "?",
            });
        }
        reloadPage(wait1s);
    }, [filters]);
    return __assign(__assign({}, statusInfo), { statusInfo: statusInfo,
        setStatusInfo: setStatusInfo,
        registerOnInit: registerOnInit,
        registerOnInitError: registerOnInitError,
        getParamsResolve: getParamsResolve,
        registerResolveParams: registerResolveParams,
        $destroy: $destroy,
        reloadPage: reloadPage,
        registerOnSearch: registerOnSearch,
        skeletonResources: skeletonResources,
        resources: resources,
        resourcesTotal: resourcesTotal,
        removeResource: removeResource,
        removeManyResources: removeManyResources,
        filters: filters,
        setFilters: setFilters,
        limit: limit,
        setHandleRequestBody: setHandleRequestBody,
        setHandleFilterToQuery: setHandleFilterToQuery,
        setHandleQueryToFilter: setHandleQueryToFilter,
        setPage: setPage,
        setOffset: setOffset,
        setSort: setSort,
        loadNextPage: loadNextPage,
        reloadResources: reloadResources,
        resetPageViewList: resetPageViewList });
}
exports.useViewList = useViewList;
//# sourceMappingURL=useViewList.js.map