"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 __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 react_1 = __importStar(require("react"));
const TableBasic_1 = require("./TableBasic");
const TablePagination_1 = require("./TablePagination");
const Box_1 = require("../Box");
exports.TableSubset = (_a) => {
    var { data: dataProp, fetchData, pageSize = 10, pageSizes, pageStart: pageStartProp, canSkip, resetOn, isLoading: isLoadingProp } = _a, tableProps = __rest(_a, ["data", "fetchData", "pageSize", "pageSizes", "pageStart", "canSkip", "resetOn", "isLoading"]);
    const [isLoading, setIsLoading] = react_1.useState(false);
    const [lastUpdate, setLastUpdate] = react_1.useState(new Date().toLocaleString());
    const [currentData, setCurrentData] = react_1.useState(dataProp ? dataProp.data : []);
    const [canPreviousPage, setCanPreviousPage] = react_1.useState(pageStartProp !== undefined && pageStartProp > 0);
    const [canNextPage, setCanNextPage] = react_1.useState(dataProp ? dataProp.next !== null : true);
    const [currentPageIndex, setCurrentPageIndex] = react_1.useState(pageStartProp !== undefined ? pageStartProp / pageSize : 0);
    const [pageStart, setPageStart] = react_1.useState(pageStartProp !== undefined ? pageStartProp : currentPageIndex * pageSize);
    const [dataCount, setDataCount] = 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* () {
        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());
    };
    const reset = () => {
        setDataCount(0);
        setCurrentPageIndex(0);
        setCanPreviousPage(false);
        setCanNextPage(false);
        setCurrentData([]);
        setLastUpdate(new Date().toLocaleString());
        setPageStart(0);
        getData(0);
    };
    react_1.useEffect(() => {
        if (dataProp)
            setTableState(dataProp);
    }, [dataProp]); // eslint-disable-line
    react_1.useEffect(() => {
        if (resetOn)
            reset();
    }, [resetOn]); // eslint-disable-line
    const paginationProps = {
        canPreviousPage,
        canNextPage,
        gotoPage: goToPage,
        nextPage,
        previousPage,
        totalRows: dataCount,
        pageIndex: currentPageIndex,
        pageSize,
        pageSizes,
        pageCount: getPageCount(dataCount),
        canSkip,
    };
    return (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement(TableBasic_1.TableBasic, Object.assign({ data: currentData, refresh: refresh, lastUpdate: lastUpdate, isLoading: isLoading || isLoadingProp }, tableProps)),
        !isLoading && !isLoadingProp && currentData.length > 0 && (react_1.default.createElement(Box_1.Box, { mt: "l" },
            react_1.default.createElement(TablePagination_1.TablePagination, Object.assign({}, paginationProps))))));
};
//# sourceMappingURL=TableSubset.js.map