import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { createContext, useContext, useEffect, useMemo } from 'react';
import { ErrorBox, useFetch, useToast } from '@vertesia/ui/core';
import { useUserSession } from '@vertesia/ui/session';
import { useDocumentSearch, useDocumentSelection } from '../../../store';
import { AddToCollectionAction } from './actions/AddToCollectionAction';
import { ChangeTypeAction } from './actions/ChangeTypeAction';
import { DeleteObjectsAction, DeleteObjectsFromCollectionsAction } from './actions/DeleteObjectsAction';
import { ExportPropertiesAction } from './actions/ExportPropertiesAction';
import { RemoveFromCollectionAction } from './actions/RemoveFromCollectionAction';
import { StartWorkflowAction, StartWorkflowComponent } from './actions/StartWorkflowComponent';
export class ObjectsActionContext {
    params;
    allActions = [
        ExportPropertiesAction,
        ChangeTypeAction,
        StartWorkflowAction,
        AddToCollectionAction,
        DeleteObjectsAction,
        RemoveFromCollectionAction,
        DeleteObjectsFromCollectionsAction
    ];
    wfRules = [];
    callbacks = {};
    startWorkflow;
    constructor(params) {
        this.params = params;
    }
    get actions() {
        const isInCollection = !!this.params.selection?.collectionId;
        if (isInCollection) {
            return this.allActions.filter(action => action.id !== 'addToCollection' && action.id !== 'delete');
        }
        else {
            return this.allActions.filter(action => action.id !== 'removeFromCollection' && action.id !== 'deleteFromCollections');
        }
    }
    async loadWorkflows() {
        this.params.client.workflows.rules.list().then((rules) => {
            this.wfRules = rules.map(rule => ({
                id: rule.id,
                name: rule.name,
                description: rule.description,
                confirm: false,
                isWorkflow: true,
                component: StartWorkflowComponent
            })).sort((a, b) => a.name.localeCompare(b.name));
        });
        return this.wfRules;
    }
    registerCallback(name, cb) {
        this.callbacks[name] = cb;
        return () => {
            delete this.callbacks[name];
        };
    }
    unregisterCallback(name) {
        delete this.callbacks[name];
    }
    findAction(actionId) {
        let action = this.allActions.find(a => a.id === actionId);
        if (!action) {
            action = this.wfRules.find(a => a.id === actionId);
        }
        return action;
    }
    async run(actionId) {
        const action = this.findAction(actionId);
        if (!action) {
            throw new Error(`Action ${actionId} not found`);
        }
        const params = { ...this.params, action };
        // if (action.isWorkflow) {
        //     if (!this.startWorkflow) {
        //         throw new Error("No startWorkflow callback set");
        //     }
        //     return this.startWorkflow(params);
        // } else {
        const cb = this.callbacks[actionId];
        if (cb) {
            return cb(params);
        }
        else {
            throw new Error("No action callback set");
        }
        //        }
    }
}
const ObjectsActionContextReact = createContext(undefined);
export function ObjectsActionContextProvider({ children }) {
    const selection = useDocumentSelection();
    const toast = useToast();
    const { client } = useUserSession();
    const search = useDocumentSearch();
    const { data: rules, error } = useFetch(() => {
        return client.workflows.rules.list().then((rules) => {
            return rules.map(rule => ({
                id: rule.id,
                name: rule.name,
                description: rule.description,
                confirm: false,
                isWorkflow: true,
                component: StartWorkflowComponent
            })).sort((a, b) => a.name.localeCompare(b.name));
        });
    }, []);
    const context = useMemo(() => {
        const context = new ObjectsActionContext({
            selection, toast, client, search
        });
        context.wfRules = rules;
        return context;
    }, [selection, rules]);
    if (error) {
        return _jsx(ErrorBox, { title: "Failed to fetch workflows", children: error.message });
    }
    return (context && (_jsxs(ObjectsActionContextReact.Provider, { value: context, children: [_jsx(Actions, {}), children] })));
}
function Actions({}) {
    const context = useObjectsActionContext();
    const selection = context.params.selection;
    const objectId = selection.getObjectId();
    const objectIds = selection.isSingleSelection() && objectId ? [objectId] : selection.getObjectIds();
    return (_jsx("div", { style: { display: 'none' }, children: context.allActions.map(action => (_jsx(action.component, { action: action, objectIds: objectIds, collectionId: selection.collectionId }, action.id))) }));
}
export function useObjectsActionContext() {
    const ctx = useContext(ObjectsActionContextReact);
    if (!ctx) {
        throw new Error("You cannot use useActionContext outside an ActionProvider");
    }
    return ctx;
}
export function useObjectsActionCallback(name, cb) {
    const ctx = useObjectsActionContext();
    useEffect(() => {
        return ctx.registerCallback(name, cb);
    }, [ctx, name, cb]);
    return ctx;
}
export function useStartWorkflowCallback(cb) {
    const ctx = useObjectsActionContext();
    useEffect(() => {
        ctx.startWorkflow = cb;
        return () => {
            ctx.startWorkflow = undefined;
        };
    }, [cb, ctx]);
    return ctx;
}
//# sourceMappingURL=ObjectsActionContext.js.map