"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 __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 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useSavedSearchesRequest = void 0;
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var ramda_1 = require("ramda");
var react_1 = require("react");
var PageRequestsAbortingContext_1 = require("../../contexts/PageRequestsAbortingContext");
var types_1 = require("../../types");
var errors_1 = require("../../helpers/errors");
var helpers_1 = require("./helpers");
var useSavedSearchesRequest = function (_a) {
    var options = _a.options, defaultRowsPerPage = _a.defaultRowsPerPage, queryEstimatorEnabled = _a.queryEstimatorEnabled;
    var _b = (0, react_1.useState)(0), page = _b[0], setPage = _b[1];
    var _c = (0, react_1.useState)(defaultRowsPerPage), rowsPerPage = _c[0], setRowsPerPage = _c[1];
    var _d = (0, react_1.useState)([]), data = _d[0], setData = _d[1];
    var _e = (0, react_1.useState)(0), total = _e[0], setTotal = _e[1];
    var _f = (0, react_1.useState)({}), profilesCountMap = _f[0], setProfilesCountMap = _f[1];
    var _g = (0, react_1.useState)({
        loading: types_1.RequestStates.INIT,
        creating: types_1.RequestStates.INIT,
        updating: types_1.RequestStates.INIT,
        deleting: types_1.RequestStates.INIT
    }), requestsStates = _g[0], setRequestsStates = _g[1];
    var signal = (0, react_1.useContext)(PageRequestsAbortingContext_1.PageRequestsAbortingContext);
    var allOptions = (0, react_1.useMemo)(function () { return (__assign(__assign({}, options), { max: rowsPerPage, offset: rowsPerPage * page })); }, [options, page, rowsPerPage]);
    var savedSearchesWithCount = (0, react_1.useMemo)(function () {
        return data.map(function (savedSearch) {
            var _a;
            var _b = (_a = profilesCountMap[savedSearch.uri]) !== null && _a !== void 0 ? _a : {}, count = _b.count, isLoading = _b.isLoading;
            var savedSearchWithCount = __assign({}, savedSearch);
            if (!(0, ramda_1.isNil)(count))
                savedSearchWithCount.count = count;
            if (!(0, ramda_1.isNil)(isLoading))
                savedSearchWithCount.isLoadingTotal = isLoading;
            return savedSearchWithCount;
        });
    }, [data, profilesCountMap]);
    var updateRequestState = (0, react_1.useCallback)(function (type, state) {
        setRequestsStates(function (prevRequestsStates) {
            var _a;
            return (__assign(__assign({}, prevRequestsStates), (_a = {}, _a[type] = state, _a)));
        });
    }, []);
    var loadSavedSearches = (0, react_1.useCallback)(function () { return __awaiter(void 0, void 0, void 0, function () {
        var countResults, restOptions, _a, _b, savedSearches, total_1, totals, error_1;
        return __generator(this, function (_c) {
            switch (_c.label) {
                case 0:
                    updateRequestState('loading', types_1.RequestStates.LOADING);
                    _c.label = 1;
                case 1:
                    _c.trys.push([1, 5, , 6]);
                    countResults = allOptions.countResults, restOptions = __rest(allOptions, ["countResults"]);
                    return [4 /*yield*/, (0, mdm_sdk_1.getSavedSearches)(restOptions, signal)];
                case 2:
                    _a = _c.sent(), _b = _a.result, savedSearches = _b === void 0 ? [] : _b, total_1 = _a.total;
                    if (!countResults) return [3 /*break*/, 4];
                    return [4 /*yield*/, (0, helpers_1.getTotalsForSavedSearches)(savedSearches, queryEstimatorEnabled, signal)];
                case 3:
                    totals = _c.sent();
                    setProfilesCountMap(totals);
                    _c.label = 4;
                case 4:
                    setData(savedSearches || []);
                    setTotal(total_1);
                    updateRequestState('loading', types_1.RequestStates.LOADED);
                    return [3 /*break*/, 6];
                case 5:
                    error_1 = _c.sent();
                    console.warn(error_1);
                    if (!(0, mdm_sdk_1.isAbortError)(error_1)) {
                        updateRequestState('loading', types_1.RequestStates.ERROR);
                        setData([]);
                    }
                    return [3 /*break*/, 6];
                case 6: return [2 /*return*/];
            }
        });
    }); }, [allOptions, signal, queryEstimatorEnabled, updateRequestState]);
    var loadTotalForUri = (0, react_1.useCallback)(function (uri) { return __awaiter(void 0, void 0, void 0, function () {
        var savedSearch, total_2, e_1;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    savedSearch = data.find((0, ramda_1.propEq)('uri', uri));
                    setProfilesCountMap((0, ramda_1.assocPath)([uri, 'isLoading'], true));
                    _a.label = 1;
                case 1:
                    _a.trys.push([1, 3, 4, 5]);
                    return [4 /*yield*/, (0, mdm_sdk_1.getTotalsForQuery)((0, mdm_sdk_1.replacePlaceholdersInQuery)(savedSearch.query), false, signal)];
                case 2:
                    total_2 = (_a.sent()).total;
                    setProfilesCountMap((0, ramda_1.assocPath)([uri, 'count'], total_2));
                    return [3 /*break*/, 5];
                case 3:
                    e_1 = _a.sent();
                    console.warn(e_1);
                    return [3 /*break*/, 5];
                case 4:
                    setProfilesCountMap((0, ramda_1.assocPath)([uri, 'isLoading'], false));
                    return [7 /*endfinally*/];
                case 5: return [2 /*return*/];
            }
        });
    }); }, [data, signal]);
    var createSearch = (0, react_1.useCallback)(function (savedSearch) { return __awaiter(void 0, void 0, void 0, function () {
        var type, result, error_2;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    updateRequestState('creating', types_1.RequestStates.LOADING);
                    _a.label = 1;
                case 1:
                    _a.trys.push([1, 3, , 4]);
                    type = allOptions.type;
                    return [4 /*yield*/, (0, mdm_sdk_1.createSavedSearch)([__assign(__assign({}, savedSearch), { type: type })])];
                case 2:
                    result = _a.sent();
                    if (page === 0) {
                        loadSavedSearches();
                    }
                    else {
                        setPage(0);
                    }
                    updateRequestState('creating', types_1.RequestStates.LOADED);
                    return [2 /*return*/, { success: true, result: result }];
                case 3:
                    error_2 = _a.sent();
                    (0, errors_1.showDefaultErrorMessage)(error_2);
                    updateRequestState('creating', types_1.RequestStates.ERROR);
                    return [2 /*return*/, { success: false, error: error_2 }];
                case 4: return [2 /*return*/];
            }
        });
    }); }, [allOptions, page, updateRequestState, loadSavedSearches]);
    var updateSearch = (0, react_1.useCallback)(function (savedSearch, shouldReloadTotal) { return __awaiter(void 0, void 0, void 0, function () {
        var result, newSavedSearch_1, error_3;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    updateRequestState('updating', types_1.RequestStates.LOADING);
                    _a.label = 1;
                case 1:
                    _a.trys.push([1, 3, , 4]);
                    return [4 /*yield*/, (0, mdm_sdk_1.updateSavedSearch)(savedSearch)];
                case 2:
                    result = _a.sent();
                    if (shouldReloadTotal) {
                        setProfilesCountMap((0, ramda_1.assocPath)([savedSearch.uri, 'count'], undefined));
                    }
                    newSavedSearch_1 = shouldReloadTotal ? (0, ramda_1.omit)(['count'], savedSearch) : savedSearch;
                    setData(function (prevData) { return prevData.map(function (item) { return (item.uri === savedSearch.uri ? newSavedSearch_1 : item); }); });
                    updateRequestState('updating', types_1.RequestStates.LOADED);
                    return [2 /*return*/, { success: true, result: result }];
                case 3:
                    error_3 = _a.sent();
                    (0, errors_1.showDefaultErrorMessage)(error_3);
                    updateRequestState('updating', types_1.RequestStates.ERROR);
                    return [2 /*return*/, { success: false, error: error_3 }];
                case 4: return [2 /*return*/];
            }
        });
    }); }, [updateRequestState]);
    var deleteSearch = (0, react_1.useCallback)(function (uri) { return __awaiter(void 0, void 0, void 0, function () {
        var result, error_4;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    updateRequestState('deleting', types_1.RequestStates.LOADING);
                    _a.label = 1;
                case 1:
                    _a.trys.push([1, 3, , 4]);
                    return [4 /*yield*/, (0, mdm_sdk_1.deleteSavedSearch)({ uri: uri })];
                case 2:
                    result = _a.sent();
                    loadSavedSearches();
                    updateRequestState('deleting', types_1.RequestStates.LOADED);
                    return [2 /*return*/, { success: true, result: result }];
                case 3:
                    error_4 = _a.sent();
                    (0, errors_1.showDefaultErrorMessage)(error_4);
                    updateRequestState('deleting', types_1.RequestStates.ERROR);
                    return [2 /*return*/, { success: false, error: error_4 }];
                case 4: return [2 /*return*/];
            }
        });
    }); }, [updateRequestState, loadSavedSearches]);
    (0, react_1.useEffect)(function () {
        loadSavedSearches();
    }, [loadSavedSearches]);
    return {
        states: requestsStates,
        data: savedSearchesWithCount,
        total: total,
        page: page,
        rowsPerPage: rowsPerPage,
        updatePage: setPage,
        updateRowsPerPage: setRowsPerPage,
        reload: loadSavedSearches,
        loadTotalForSearchByUri: loadTotalForUri,
        createSearch: createSearch,
        updateSearch: updateSearch,
        deleteSearch: deleteSearch
    };
};
exports.useSavedSearchesRequest = useSavedSearchesRequest;
