import { jsx as _jsx, jsxs as _jsxs } from "@emotion/react/jsx-runtime";
import { Box } from "@chakra-ui/react";
import * as queryString from "./utils/query-string";
import { Navigate, Route, Routes, useLocation } from "react-router-dom";
import ActivePageContainer from "./ActivePageContainer";
import qore from "./hooks/qore";
import { VariablesProvider, useQRScannerAction, RuntimeContext, } from "@qorebase/app-component";
import { AnimatePresence } from "framer-motion";
import { Scene } from "./Composer";
import React from "react";
import { ToastNotificationContextProvider } from "./ToastNotification";
import { RuntimeInputProvider } from "./RuntimeInput";
import { useEvaluateLazy } from "./hooks/useExpression";
import { PageSchemaLoader } from "./hooks/useFetchPage";
import { useSourceHooks } from "./hooks/sourceHooks/useSourceHooks";
import { usePageSource } from "./hooks/usePageSource";
import { fakeRow } from "./ActivePage";
import { usePageParam } from "./hooks/usePageParam";
export default function RuntimeContents() {
    const config = RuntimeContext.useSelectState((state) => state.config);
    const access_token = React.useMemo(() => localStorage === null || localStorage === void 0 ? void 0 : localStorage.getItem(`${config.projectID}_user_token`), [config.projectID]);
    const redirectPage = RuntimeContext.useSelectState((state) => {
        var _a, _b;
        return access_token
            ? (_a = state.config.initialPage) === null || _a === void 0 ? void 0 : _a.loggedInPage
            : (_b = state.config.initialPage) === null || _b === void 0 ? void 0 : _b.entryPage;
    });
    const pagesMap = RuntimeContext.useSelectState((state) => state.maps.page);
    const pageID = usePageParam();
    const page = RuntimeContext.useSelectState((state) => state.maps.page[pageID]);
    const location = useLocation();
    const client = qore.useClient();
    const { user: originalUser } = qore.useCurrentUser();
    const { source } = usePageSource({ page });
    const sourceHooks = useSourceHooks(source);
    const { data } = sourceHooks.useFetch();
    const { code } = useQRScannerAction();
    const firstRow = data || fakeRow;
    const mergedRow = React.useMemo(() => {
        return Object.assign(Object.assign({}, code), firstRow);
    }, [firstRow, code]);
    const user = React.useMemo(() => originalUser &&
        Object.fromEntries(Object.entries(originalUser).map(([key, val]) => [
            key,
            val && typeof val === "object" && "filename" in val
                ? `${client.project.config.endpoint}/v1/files/public/users/${originalUser.id}/${key}/${
                // @ts-ignore
                val.filename}`
                : val,
        ])), [originalUser, client.project.config.endpoint]);
    const [state, setState] = React.useState({ location: "0,0" });
    const userVariables = React.useMemo(() => {
        if (!user)
            return {};
        const userVar = {
            current_location: state.location,
        };
        return Object.fromEntries(Object.entries(user).map(([key, value]) => [
            `user.${key}`,
            key === "role" ? (value === null || value === void 0 ? void 0 : value.name) || value : value,
        ], userVar));
    }, [user, state.location, location.search]);
    const evaluate = useEvaluateLazy();
    const variables = React.useMemo(() => {
        var _a, _b;
        const parsed = queryString.parse(location.search);
        const rowId = (parsed === null || parsed === void 0 ? void 0 : parsed.rowId)
            ? parsed === null || parsed === void 0 ? void 0 : parsed.rowId
            : ((_a = page === null || page === void 0 ? void 0 : page.defaultRow) === null || _a === void 0 ? void 0 : _a.type) === "row-id"
                ? evaluate((_b = page === null || page === void 0 ? void 0 : page.defaultRow) === null || _b === void 0 ? void 0 : _b.rowId, Object.assign(Object.assign({}, userVariables), mergedRow))
                : "";
        const modalRowId = (parsed === null || parsed === void 0 ? void 0 : parsed.modalRowId) || "";
        return Object.assign(Object.assign(Object.assign({}, userVariables), mergedRow), { rowId, modalRowId });
    }, [userVariables, mergedRow, location.search, page, evaluate]);
    // React.useEffect(function getLocation() {
    //   const watchId = navigator.geolocation
    //     ? navigator.geolocation.watchPosition((position) => {
    //         setState((state) =>
    //           produce(state, (draft) => {
    //             draft.location = `${position.coords.latitude},${position.coords.longitude}`;
    //           })
    //         );
    //       })
    //     : null;
    //   return () => {
    //     navigator.geolocation?.clearWatch(watchId);
    //   };
    // }, []);
    const firstPageNavigate = React.useMemo(() => pagesMap[redirectPage]
        ? redirectPage
        : Object.keys(pagesMap).filter((page) => page !== "login")[0], [pagesMap, pagesMap, redirectPage]);
    return (_jsx(ToastNotificationContextProvider, { children: _jsx(AnimatePresence, Object.assign({ initial: false, mode: "wait" }, { children: _jsxs(Routes, Object.assign({ location: location }, { children: [firstPageNavigate && (_jsx(Route, { path: "/", element: _jsx(Scene, { children: _jsx(Navigate, { to: `/page/${firstPageNavigate}` }) }) })), _jsx(Route, { path: "/page/:page", element: _jsx(Box, Object.assign({ position: "absolute", top: 0, left: 0, right: 0, bottom: 0, overflow: "unset" }, { children: _jsx(VariablesProvider, Object.assign({ values: variables }, { children: _jsx(RuntimeInputProvider, { children: _jsx(PageSchemaLoader, { children: _jsx(ActivePageContainer, {}) }) }) })) })) })] }), location.pathname) })) }));
}
//# sourceMappingURL=RuntimeContents.js.map