import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCubeMeta, useDryRun } from '@cubejs-client/react';
import { createContext, useContext, useEffect, useState, } from 'react';
import { useToggle } from '../hooks';
import { SchemaFormat } from '../types';
import { RollupDesignerModal } from './components/RollupDesignerModal';
export const Context = createContext({});
export function RollupDesignerContext({ cubeApi, children, ...props }) {
    const [isModalOpen, toggleModal] = useToggle();
    const [error, setError] = useState(null);
    const [query, setQuery] = useState(null);
    const [transformedQuery, setTransformedQuery] = useState(null);
    const [memberTypeCubeMap, setMemberTypeCubeMap] = useState({
        measures: [],
        dimensions: [],
        segments: [],
        timeDimensions: [],
    });
    const metaResult = useCubeMeta({
        skip: !isModalOpen,
        cubeApi,
    });
    const dryRunResult = useDryRun(query, {
        skip: !isModalOpen || !query,
        cubeApi,
    });
    useEffect(() => {
        const { isLoading, error, response } = metaResult;
        if (!isLoading) {
            if (response) {
                setMemberTypeCubeMap(response.membersGroupedByCube());
            }
            else if (error) {
                setError(error);
            }
        }
    }, [metaResult.isLoading]);
    useEffect(() => {
        const { isLoading, error, response } = dryRunResult;
        if (!isLoading) {
            if (response) {
                setTransformedQuery(response.transformedQueries[0]);
            }
            else if (error) {
                setError(error);
            }
        }
    }, [dryRunResult.isLoading]);
    function reset() {
        setTransformedQuery(null);
        setError(null);
    }
    return (_jsxs(Context.Provider, { value: {
            isLoading: metaResult.isLoading || dryRunResult.isLoading,
            isModalOpen,
            toggleModal,
            query,
            setQuery,
            transformedQuery,
            setTransformedQuery,
            memberTypeCubeMap,
            error,
            defaultSchemaFormat: props.defaultSchemaFormat || SchemaFormat.js
        }, children: [children, _jsx(RollupDesignerModal, { apiUrl: props.apiUrl, token: props.token, onAfterClose: reset })] }));
}
export function useRollupDesignerContext() {
    return useContext(Context);
}
//# sourceMappingURL=Context.js.map