"use strict";
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 __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.TableSubset = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const TableBasic_1 = require("./TableBasic");
const TablePagination_1 = require("./TablePagination");
const Box_1 = require("../Box");
const TableSubset = (_a) => {
    var { data: dataProp, fetchData, pageSize: pageSizeProp, pageSizes, pageStart: pageStartProp, canSkipPage, resetOn, isLoading: isLoadingProp, setPageSize, paginationLabel, onRefresh } = _a, tableProps = __rest(_a, ["data", "fetchData", "pageSize", "pageSizes", "pageStart", "canSkipPage", "resetOn", "isLoading", "setPageSize", "paginationLabel", "onRefresh"]);
    const pageSize = pageSizeProp || 10;
    const [isLoading, setIsLoading] = (0, react_1.useState)(false);
    const [lastUpdate, setLastUpdate] = (0, react_1.useState)(new Date().toLocaleString());
    const [currentData, setCurrentData] = (0, react_1.useState)(dataProp ? dataProp.data : []);
    const [canPreviousPage, setCanPreviousPage] = (0, react_1.useState)(pageStartProp !== undefined && pageStartProp > 0);
    const [canNextPage, setCanNextPage] = (0, react_1.useState)(dataProp ? dataProp.next !== null : true);
    const [currentPageIndex, setCurrentPageIndex] = (0, react_1.useState)(pageStartProp !== undefined ? pageStartProp / pageSize : 0);
    const [pageStart, setPageStart] = (0, react_1.useState)(pageStartProp !== undefined ? pageStartProp : currentPageIndex * pageSize);
    const [dataCount, setDataCount] = (0, react_1.useState)(dataProp ? dataProp.count : 0);
    const getPageCount = (count) => Math.ceil(count / pageSize);
    const setTableState = (newData) => {
        const { data, count, next } = newData;
        if (data)
            setCurrentData(data);
        if (count)
            setDataCount(count);
        setCanNextPage(next !== null);
        if (dataProp)
            setIsLoading(false);
    };
    const getData = (start) => __awaiter(void 0, void 0, void 0, function* () {
        if (!fetchData) {
            return;
        }
        setIsLoading(true);
        const fetchResult = yield fetchData({ start });
        if (!dataProp) {
            setTableState(fetchResult);
            setIsLoading(false);
        }
    });
    const goToPage = (targetPage) => {
        setCurrentPageIndex(targetPage);
        setPageStart(targetPage * pageSize);
        getData(targetPage * pageSize);
        if (targetPage === 0) {
            setCanPreviousPage(false);
            setCanNextPage(true);
        }
        else {
            setCanPreviousPage(true);
        }
    };
    const previousPage = () => {
        goToPage(currentPageIndex - 1);
        setCanNextPage(true);
    };
    const nextPage = () => {
        goToPage(currentPageIndex + 1);
    };
    const refresh = () => {
        getData(pageStart);
        setLastUpdate(new Date().toLocaleString());
        if (onRefresh)
            onRefresh();
    };
    const reset = () => {
        setDataCount(0);
        setCurrentPageIndex(0);
        setCanPreviousPage(false);
        setCanNextPage(false);
        setCurrentData([]);
        setLastUpdate(new Date().toLocaleString());
        setPageStart(0);
        getData(0);
    };
    (0, react_1.useEffect)(() => {
        if (dataProp)
            setTableState(dataProp);
    }, [dataProp]);
    (0, react_1.useEffect)(() => {
        if (resetOn)
            reset();
    }, [resetOn]);
    const paginationProps = {
        canPreviousPage,
        canNextPage,
        gotoPage: canSkipPage ? goToPage : null,
        nextPage,
        previousPage,
        totalRows: dataCount,
        pageIndex: currentPageIndex,
        pageSize,
        pageSizes,
        pageCount: getPageCount(dataCount),
        setPageSize,
        label: paginationLabel,
    };
    return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(TableBasic_1.TableBasic, Object.assign({ data: currentData, refresh: refresh, lastUpdate: lastUpdate, isLoading: isLoading || isLoadingProp }, tableProps), void 0), pageSizeProp && !isLoading && !isLoadingProp && currentData.length > 0 && ((0, jsx_runtime_1.jsx)(Box_1.Box, Object.assign({ variant: "raw", margin: "l 0 0 0" }, { children: (0, jsx_runtime_1.jsx)(TablePagination_1.TablePagination, Object.assign({}, paginationProps), void 0) }), void 0))] }, void 0));
};
exports.TableSubset = TableSubset;
//# sourceMappingURL=TableSubset.js.map