import React from "react";
import { SourceContext, ModalPageSourceContext, useVariablesContext, RuntimeContext, useTemplate, } from "@qorebase/app-component";
import { useLocation, useParams } from "react-router-dom";
import format from "../utils/format";
export const useSource = () => React.useContext(SourceContext);
export const useModalPageSource = () => React.useContext(ModalPageSourceContext);
export function usePageSource(customPage, customRowId) {
    var _a, _b, _c;
    const location = useLocation();
    const defaultPage = RuntimeContext.useSelectState((state) => state.maps.page);
    const params = useParams();
    const page = React.useMemo(() => (customPage ? customPage.page : defaultPage[params.page]), [customPage, defaultPage, params.page]);
    const { values: row } = useVariablesContext();
    const defaultRowID = useTemplate(((_a = page === null || page === void 0 ? void 0 : page.defaultRow) === null || _a === void 0 ? void 0 : _a.type) === "row-id"
        ? ((_b = page === null || page === void 0 ? void 0 : page.defaultRow) === null || _b === void 0 ? void 0 : _b.rowId)
            ? (_c = page === null || page === void 0 ? void 0 : page.defaultRow) === null || _c === void 0 ? void 0 : _c.rowId
            : ""
        : "");
    const source = React.useMemo(() => {
        var _a;
        const target = page === null || page === void 0 ? void 0 : page.sourceID;
        const rowId = customRowId || row.rowId || defaultRowID;
        return {
            rowId: customRowId || row.rowId,
            type: "record",
            target,
            defaultRow: !(page === null || page === void 0 ? void 0 : page.defaultRow)
                ? { type: "first-row" }
                : ((_a = page === null || page === void 0 ? void 0 : page.defaultRow) === null || _a === void 0 ? void 0 : _a.type) === "row-id"
                    ? { type: "row-id", rowId: defaultRowID }
                    : { type: "first-row" },
            params: Object.fromEntries(Object.entries((page === null || page === void 0 ? void 0 : page.sourceParams) || {}).map(([key, val]) => [
                key,
                format(val.toString(), Object.assign(Object.assign({}, row), { rowId })),
            ])),
            prefetch: page === null || page === void 0 ? void 0 : page.prefetch,
        };
    }, [
        location.search,
        page === null || page === void 0 ? void 0 : page.sourceID,
        defaultRowID,
        page === null || page === void 0 ? void 0 : page.defaultRow,
        page === null || page === void 0 ? void 0 : page.sourceParams,
        page === null || page === void 0 ? void 0 : page.prefetch,
        row,
        customRowId,
    ]);
    return { source, row, page };
}
//# sourceMappingURL=useSource.js.map