import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { toast } from "sonner";
import uuid from "react-uuid";
import { getItemDescriptor } from "../utils";
import { ItemNameDialog } from "../ui/ItemNameDialogNew";
import { exportItems as exportItemsService, } from "../services/contentService";
import { editOperationNeedsTerminalCompletion, waitForEditOperationTerminal, } from "../client/waitForEditOperationTerminal";
import { CopyMoveTargetSelectorDialog, } from "../ui/CopyMoveTargetSelectorDialog";
import { ExportItemsDialog, } from "../ui/ExportItemsDialog";
import { ImportItemsDialog, } from "../ui/ImportItemsDialog";
import { PublishItemDialog } from "../ui/PublishItemDialog";
import { PublishRestrictionsDialog } from "../ui/PublishRestrictionsDialog";
import { TemplateSelectorDialog, } from "../ui/TemplateSelectorDialog";
import { localStorageService } from "../services/localStorageService";
import { TriangleAlert, Pencil, Plus, ClipboardCheck, ArrowRight, Copy, Download, Upload, CopyPlus, GitBranch, RefreshCw, CheckCircle2, FileText, } from "lucide-react";
import { DeleteIcon } from "../../components/ui/delete-icon";
import { executeChangeTemplate } from "../services/editService";
import { CreateReviewDialog } from "../reviews/CreateReviewDialog";
// Template Template ID constant
const TEMPLATE_TEMPLATE_ID = "AB86861A-6030-46C5-B394-E8F99E8B87DB";
const SOURCE_FIELD_ID = "1dcc237e-d653-45b0-9a45-89ff6a9036a3";
// Helper function to normalize GUID for comparison (removes braces and converts to uppercase)
const normalizeGuid = (guid) => {
    if (!guid)
        return "";
    return guid.replace(/[{}]/g, "").toUpperCase();
};
function CreateReviewDialogWrapper({ onClose, initialItems, }) {
    return (_jsx(CreateReviewDialog, { open: true, onOpenChange: (open) => {
            if (!open)
                onClose(null);
        }, onCreated: (reviewId) => onClose(reviewId), initialItems: initialItems }));
}
export const deleteItemCommand = {
    id: "deleteItem",
    label: "Delete",
    icon: _jsx(DeleteIcon, { size: "md" }),
    keyBinding: {
        key: "Delete",
    },
    disabled: (context) => !context.data?.items || !context.data?.items[0]?.canDelete || false,
    execute: async (context) => {
        const items = context.data?.items;
        if (!items || items.length === 0)
            return;
        const shouldNavigateToParent = items.some((x) => context.editContext.item?.descriptor.id === x.id);
        // The confirmation dialog (with reference checking) is handled inside deleteItems
        const deleted = await context.editContext.operations.deleteItems(items.map((x) => x.descriptor));
        if (!deleted)
            return;
        // Navigate to parent only after deletion is confirmed and completed
        if (shouldNavigateToParent) {
            const firstItem = items[0];
            if (firstItem) {
                context.editContext.loadItem({
                    id: firstItem.parentId,
                    language: context.editContext.item?.language ??
                        context.editContext.currentItemDescriptor?.language ??
                        "en",
                    version: 0,
                });
            }
        }
        return true;
    },
};
export const renameItemCommand = {
    id: "renameItem",
    label: "Rename",
    icon: _jsx(Pencil, { strokeWidth: 1 }),
    keyBinding: {
        key: "F2",
    },
    disabled: (context) => !context.data?.items ||
        context.data.items.length !== 1 ||
        !context.data.items[0]?.canRename ||
        false,
    execute: async (context) => {
        const item = context.data?.items[0];
        if (!item)
            return;
        const newName = await context.openDialog(ItemNameDialog, {
            name: item.name,
            title: "Rename Item",
            message: "Enter a new name for the item:",
            headerIcon: _jsx(Pencil, { strokeWidth: 1 }),
            parentItem: { ...item.descriptor, id: item.parentId },
            itemId: item.id,
        });
        if (newName) {
            await context.editContext.operations.renameItem(item.descriptor, newName);
        }
    },
};
export const insertItemCommand = {
    id: "insertItem",
    label: "Insert Item",
    icon: _jsx(Plus, { strokeWidth: 1 }),
    disabled: (context) => !context.data?.items ||
        context.data.items.length !== 1 ||
        !context.data.items[0]?.canCreate ||
        false,
    execute: async (context) => {
        const parentItem = context.data?.items[0];
        const templateId = context.data?.templateId;
        if (!parentItem || !templateId)
            return;
        // Ensure any context overlays/menus are closed before opening the name dialog
        try {
            context.editContext.setCurrentOverlay?.(undefined);
        }
        catch { }
        const templateItem = await context.editContext.itemsRepository.getItem({
            id: templateId,
            language: "en",
            version: 0,
        });
        const templateName = templateItem?.name;
        const name = await context.openDialog(ItemNameDialog, {
            title: "Create Item",
            message: "Enter a name for the new item:",
            name: templateName,
            parentItem: parentItem.descriptor,
        });
        if (name) {
            const result = await context.editContext.operations.createItem(parentItem.descriptor, templateId, name);
            if (result) {
                await context.editContext.loadItem(result);
            }
            return result;
        }
    },
};
function getCloneSourceField(item) {
    const field = item?.fields?.find((field) => normalizeGuid(field.id) === normalizeGuid(SOURCE_FIELD_ID) ||
        field.name === "__Source");
    return field?.rawValue?.trim() ? field : undefined;
}
export const moveItemsCommand = {
    id: "moveItems",
    label: "Move item(s) to...",
    icon: _jsx(ArrowRight, { strokeWidth: 1 }),
    disabled: (context) => !context.data?.items ||
        context.data.items.some((x) => !x.canDelete) ||
        false,
    execute: async (context) => {
        const items = context.data?.items;
        let targetItem = context.data?.targetItem;
        let index = context.data?.index;
        if (!items)
            return;
        if (!targetItem) {
            const result = await context.openDialog(CopyMoveTargetSelectorDialog, {
                items: items ?? [],
                editContext: context.editContext,
                header: "Select Target Item",
                label: items?.length && items.length > 1
                    ? `Move ${items?.length} items`
                    : `Move item`,
            });
            if (result) {
                targetItem = result;
                index = -1;
            }
        }
        if (!targetItem)
            return;
        context.editContext.operations.moveItems(items.map((x) => getItemDescriptor(x)), targetItem, index ?? 0);
    },
};
export const copyItemsCommand = {
    id: "copyItems",
    label: "Copy item(s) to...",
    icon: _jsx(Copy, { strokeWidth: 1 }),
    disabled: (context) => !context.data?.items || false,
    execute: async (context) => {
        console.log("copyItemsCommand", context.data);
        const items = context.data?.items;
        let targetItem = context.data?.targetItem;
        let index = context.data?.index;
        if (!targetItem) {
            const result = await context.openDialog(CopyMoveTargetSelectorDialog, {
                items: items ?? [],
                editContext: context.editContext,
                header: "Select Target Item",
                label: items?.length && items.length > 1
                    ? `Copy ${items?.length} items`
                    : `Copy item`,
            });
            if (result) {
                targetItem = result;
                index = -1;
            }
        }
        if (!items || !targetItem)
            return;
        const result = await context.editContext.operations.copyItems(items.map((x) => getItemDescriptor(x)), targetItem, index ?? 0);
        if (result && result.length > 0 && result[0]) {
            await context.editContext.loadItem(result[0]);
        }
    },
};
export const cloneItemsCommand = {
    id: "cloneItems",
    label: "Clone item(s) to...",
    icon: _jsx(GitBranch, { strokeWidth: 1 }),
    visible: (context) => context.editContext.parheliaSettings?.itemCloningEnabled === true,
    disabled: (context) => !context.data?.items || false,
    execute: async (context) => {
        const items = context.data?.items;
        let targetItem = context.data?.targetItem;
        let index = context.data?.index;
        if (!targetItem) {
            const result = await context.openDialog(CopyMoveTargetSelectorDialog, {
                items: items ?? [],
                editContext: context.editContext,
                header: "Select Target Item",
                label: items?.length && items.length > 1
                    ? `Clone ${items.length} items`
                    : `Clone item`,
            });
            if (result) {
                targetItem = result;
                index = -1;
            }
        }
        if (!items || !targetItem)
            return;
        const sourceLanguage = items[0]?.language ?? targetItem.language;
        const result = await context.editContext.operations.cloneItems(items.map((x) => getItemDescriptor(x)), targetItem, index ?? 0);
        if (result && result.length > 0 && result[0]) {
            const clonedDescriptor = {
                id: result[0].id,
                language: result[0].language ?? sourceLanguage,
                version: result[0].version ?? 0,
            };
            await context.editContext.loadItem(clonedDescriptor, {
                forceRefresh: true,
            });
        }
    },
};
export const duplicateItemCommand = {
    id: "duplicateItem",
    label: "Duplicate item",
    icon: _jsx(CopyPlus, { strokeWidth: 1 }),
    disabled: (context) => !context.data?.items || context.data.items.length !== 1 || false,
    execute: async (context) => {
        const item = context.data?.items[0];
        console.log("item", item);
        if (!item)
            return;
        const targetItem = {
            id: item.parentId,
            language: item.language,
            version: 0,
        };
        const newName = await context.openDialog(ItemNameDialog, {
            name: `Copy of ${item.name}`,
            title: "Duplicate Item",
            message: "Enter a name for the new item:",
            headerIcon: _jsx(CopyPlus, { strokeWidth: 1 }),
            parentItem: { ...item.descriptor, id: item.parentId },
            itemId: item.id,
        });
        if (newName) {
            const result = await context.editContext.operations.duplicateItem(item.descriptor, targetItem, newName);
            if (result) {
                await context.editContext.loadItem(result);
            }
            return result;
        }
    },
};
export const uncloneItemCommand = {
    id: "uncloneItem",
    label: "Unclone item",
    icon: _jsx(GitBranch, { strokeWidth: 1 }),
    visible: (context) => {
        const item = context.data?.items?.[0];
        return (!!item && context.data?.items?.length === 1 && !!getCloneSourceField(item));
    },
    disabled: (context) => {
        const item = context.data?.items?.[0];
        const sourceField = getCloneSourceField(item);
        return (!item ||
            context.data?.items?.length !== 1 ||
            !item.canWriteItem ||
            !sourceField);
    },
    execute: async (context) => {
        const item = context.data?.items?.[0];
        const sourceField = getCloneSourceField(item);
        if (!item || !sourceField)
            return;
        const confirmed = await new Promise((resolve) => {
            context.editContext.confirm({
                message: (_jsxs("div", { children: ["Remove the clone relationship for ", _jsx("em", { children: item.name }), "?", _jsx("div", { className: "mt-4 text-sm", children: "The item will keep its current values and become a regular item." })] })),
                header: "Unclone Item",
                icon: _jsx(TriangleAlert, { strokeWidth: 1 }),
                accept: () => resolve(true),
                reject: () => resolve(false),
            });
        });
        if (!confirmed)
            return;
        await context.editContext.operations.editField({
            field: sourceField.descriptor,
            rawValue: "",
            refresh: "immediate",
        });
        const currentLoadedItem = context.editContext.item;
        if (currentLoadedItem &&
            currentLoadedItem.id === item.id &&
            currentLoadedItem.language === item.language) {
            await context.editContext.loadItem(currentLoadedItem.descriptor, {
                skipViewChange: true,
                forceRefresh: true,
            });
        }
    },
};
export const changeTemplateCommand = {
    id: "changeTemplate",
    label: "Change Template",
    icon: _jsx(RefreshCw, { strokeWidth: 1 }),
    disabled: (context) => !context.data?.items ||
        context.data.items.length !== 1 ||
        !context.data.items[0]?.canWriteItem ||
        false,
    execute: async (context) => {
        const item = context.data?.items[0];
        if (!item)
            return;
        // Open template selector dialog
        const selectedTemplate = await context.openDialog(TemplateSelectorDialog, {
            currentItem: item,
            editContext: context.editContext,
        });
        if (!selectedTemplate)
            return;
        // Show confirmation dialog with warning
        const confirmed = await new Promise((resolve) => {
            context.editContext.confirm({
                message: (_jsxs("div", { children: ["Are you sure you want to change the template of ", _jsx("em", { children: item.name }), "?", _jsxs("div", { className: "mt-4 text-sm", children: [_jsx("strong", { children: "Warning:" }), " Changing the template may result in data loss for fields that are not present in the new template."] })] })),
                header: "Change Template",
                icon: _jsx(TriangleAlert, { strokeWidth: 1 }),
                accept: () => resolve(true),
                reject: () => resolve(false),
                showCancel: true,
            });
        });
        if (!confirmed)
            return;
        try {
            // Execute the change template operation
            const result = await executeChangeTemplate(item.descriptor, selectedTemplate.id, context.editContext.sessionId);
            if (result.type === "success") {
                toast.success("Template changed successfully");
                // Save to recent templates
                const RECENT_TEMPLATES_STORAGE_KEY = "editor.recentChangeTemplates";
                const MAX_RECENT_TEMPLATES = 10;
                try {
                    const recentIds = localStorageService.getItem(RECENT_TEMPLATES_STORAGE_KEY) || [];
                    const templateId = selectedTemplate.id;
                    const updatedIds = [
                        templateId,
                        ...recentIds.filter((id) => id !== templateId),
                    ].slice(0, MAX_RECENT_TEMPLATES);
                    localStorageService.setItem(RECENT_TEMPLATES_STORAGE_KEY, updatedIds);
                }
                catch (error) {
                    console.error("Failed to save recent template:", error);
                }
                // Refresh the item in the items repository to get updated template and fields
                await context.editContext.itemsRepository.refreshItems([item.descriptor], { properties: true });
                // Reload the item in the editor context
                await context.editContext.loadItem(item.descriptor);
                // Also refresh the page view to ensure all changes are reflected
                context.editContext.requestRefresh("immediate");
            }
            else {
                toast.error(result.details || "Failed to change template");
            }
        }
        catch (error) {
            toast.error(error instanceof Error ? error.message : "Failed to change template");
        }
    },
};
export const exportItemsCommand = {
    id: "exportItem",
    label: "Export",
    icon: _jsx(Download, { strokeWidth: 1 }),
    disabled: (context) => !context.data?.items || context.data.items.length === 0 || false,
    execute: async (context) => {
        const items = context.data?.items;
        if (!items || items.length === 0)
            return;
        try {
            const exportOptions = await context.openDialog(ExportItemsDialog, { items });
            if (!exportOptions)
                return;
            const request = {
                items: items.map((item) => item.descriptor),
                versionOption: exportOptions.versionOption,
                includeSubitems: exportOptions.includeSubitems,
            };
            const response = await exportItemsService(request);
            if (response.type !== "success") {
                const errorMessage = response.summary ||
                    response.details ||
                    response.rawDetails ||
                    "Export failed";
                // Show detailed error dialog for better visibility
                context.editContext.confirm({
                    message: (_jsxs("div", { children: [_jsx("div", { style: { marginBottom: "10px" }, children: "The export operation failed:" }), _jsx("div", { style: {
                                    padding: "12px",
                                    backgroundColor: "var(--color-feedback-red-light)",
                                    borderRadius: "4px",
                                    borderLeft: "3px solid var(--color-feedback-red)",
                                    fontFamily: "monospace",
                                    fontSize: "13px",
                                    whiteSpace: "pre-wrap",
                                    wordBreak: "break-word",
                                }, children: errorMessage })] })),
                    header: "Export Failed",
                    icon: _jsx(TriangleAlert, { strokeWidth: 1 }),
                    accept: () => { },
                    rejectLabel: "Close",
                    showCancel: false,
                });
                return false;
            }
            const result = response.data;
            if (result && result.yaml) {
                // Copy YAML content to clipboard
                try {
                    if (typeof navigator !== "undefined" &&
                        navigator.clipboard &&
                        typeof navigator.clipboard.writeText === "function") {
                        await navigator.clipboard.writeText(result.yaml);
                        toast.success(`Successfully exported ${result.itemCount} item(s) to clipboard`);
                    }
                    else {
                        throw new Error("Clipboard API is not available");
                    }
                    return true;
                }
                catch (clipboardError) {
                    // Fallback: Show YAML in a dialog if clipboard access fails
                    context.editContext.confirm({
                        message: (_jsxs("div", { children: [_jsx("div", { children: "Export successful! Copy the YAML below:" }), _jsx("textarea", { readOnly: true, value: result.yaml, style: {
                                        width: "100%",
                                        height: "300px",
                                        marginTop: "10px",
                                        fontFamily: "monospace",
                                        fontSize: "12px",
                                    }, onClick: (e) => {
                                        e.target.select();
                                    } })] })),
                        header: "Export Results",
                        icon: _jsx(Copy, { strokeWidth: 1 }),
                        accept: () => { },
                        rejectLabel: "Close",
                        showCancel: false,
                    });
                    return true;
                }
            }
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
            // Show detailed error dialog
            context.editContext.confirm({
                message: (_jsxs("div", { children: [_jsx("div", { style: { marginBottom: "10px" }, children: "An error occurred during export:" }), _jsx("div", { style: {
                                padding: "12px",
                                backgroundColor: "var(--color-feedback-red-light)",
                                borderRadius: "4px",
                                borderLeft: "3px solid var(--color-feedback-red)",
                                fontFamily: "monospace",
                                fontSize: "13px",
                                whiteSpace: "pre-wrap",
                                wordBreak: "break-word",
                            }, children: errorMessage })] })),
                header: "Export Failed",
                icon: _jsx(TriangleAlert, { strokeWidth: 1 }),
                accept: () => { },
                rejectLabel: "Close",
                showCancel: false,
            });
        }
        return false;
    },
};
export const importItemsCommand = {
    id: "importItems",
    label: "Import",
    icon: _jsx(Upload, { strokeWidth: 1 }),
    disabled: (context) => !context.data?.items ||
        context.data.items.length !== 1 ||
        !context.data.items[0]?.canCreate ||
        false,
    execute: async (context) => {
        const targetItem = context.data?.items[0];
        if (!targetItem)
            return;
        try {
            const importOptions = await context.openDialog(ImportItemsDialog, { targetItem });
            if (!importOptions)
                return;
            // Create the import operation
            const op = {
                type: "import-items",
                id: uuid(),
                date: new Date().toISOString(),
                title: "Import items",
                mainItem: targetItem.descriptor,
                targetItem: targetItem.descriptor,
                yaml: importOptions.yaml,
                restoreToOriginalParents: importOptions.restoreToOriginalParents,
                canUndo: true,
            };
            // Lifecycle toasts (loading/progress/result) come from operationToasts
            let result = (await context.editContext.operations.executeEditOperation(op));
            if (editOperationNeedsTerminalCompletion(result)) {
                const terminal = await waitForEditOperationTerminal(result.id || op.id, 120_000);
                result = { ...result, ...terminal };
            }
            // Check if operation failed
            if (!result) {
                throw new Error("Import failed");
            }
            // Show detailed import report based on the operation result
            const hasFailures = (result.failureCount ?? 0) > 0;
            const successCount = result.successCount ?? 0;
            const failureCount = result.failureCount ?? 0;
            // Show result message
            if (hasFailures) {
                // Show dialog for failures
                context.editContext.confirm({
                    message: (_jsxs("div", { style: { maxHeight: "60vh", overflowY: "auto" }, children: [_jsx("div", { style: { marginBottom: "10px", fontSize: "14px" }, children: result.summary ||
                                    `Imported ${successCount} item(s), ${failureCount} item(s) failed` }), _jsx("div", { style: {
                                    marginTop: "10px",
                                    fontSize: "12px",
                                    color: "var(--color-neutral-grey-50)",
                                }, children: "This operation can be undone to remove the imported items." })] })),
                    header: "Import Results",
                    icon: _jsx(TriangleAlert, { strokeWidth: 1 }),
                    accept: () => { },
                    acceptLabel: "Ok",
                    showCancel: false,
                });
            }
            // Refresh by requesting a refresh
            context.editContext.requestRefresh("immediate");
            return result.createdItemIds;
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
            // Show detailed error dialog
            context.editContext.confirm({
                message: (_jsxs("div", { children: [_jsx("div", { style: { marginBottom: "10px" }, children: "The import operation failed:" }), _jsx("div", { style: {
                                padding: "12px",
                                backgroundColor: "var(--color-feedback-red-light)",
                                borderRadius: "4px",
                                borderLeft: "3px solid var(--color-feedback-red)",
                                fontFamily: "monospace",
                                fontSize: "13px",
                                whiteSpace: "pre-wrap",
                                wordBreak: "break-word",
                                maxHeight: "300px",
                                overflowY: "auto",
                            }, children: errorMessage })] })),
                header: "Import Failed",
                icon: _jsx(TriangleAlert, { strokeWidth: 1 }),
                accept: () => { },
                rejectLabel: "Close",
                showCancel: false,
                showAccept: false,
            });
        }
        return false;
    },
};
export const addStandardValuesCommand = {
    id: "addStandardValues",
    label: "Add Standard Values",
    icon: _jsx(FileText, { strokeWidth: 1 }),
    visible: (context) => {
        // Only show for template items
        if (!context.data?.items ||
            context.data.items.length !== 1 ||
            !context.data.items[0]) {
            return false;
        }
        const item = context.data.items[0];
        return (normalizeGuid(item.templateId) === normalizeGuid(TEMPLATE_TEMPLATE_ID));
    },
    disabled: (context) => {
        // Command is enabled when visible
        return false;
    },
    execute: async (context) => {
        const item = context.data?.items?.[0];
        if (!item)
            return;
        try {
            // Get the full item to access fields
            const fullItem = await context.editContext.itemsRepository.getItem(item.descriptor);
            if (!fullItem) {
                toast.error("Could not load item");
                return;
            }
            // Find the __Standard values field
            const standardValuesField = fullItem.fields.find((f) => f.name === "__Standard values" ||
                f.displayName === "__Standard values");
            if (!standardValuesField) {
                toast.error("Could not find __Standard values field");
                return;
            }
            // Check if field has a value
            const fieldValue = standardValuesField.value || standardValuesField.rawValue || null;
            const fieldHasValue = !!fieldValue && fieldValue !== "";
            // Try to verify if the Standard Values item exists by attempting to load it
            let standardValuesItemId = fieldValue;
            let standardValuesItemExists = false;
            if (fieldHasValue && typeof fieldValue === "string") {
                try {
                    const existingItem = await context.editContext.itemsRepository.getItem({
                        id: fieldValue,
                        language: item.language,
                        version: 0,
                    });
                    if (existingItem && existingItem.name === "__Standard Values") {
                        standardValuesItemExists = true;
                        standardValuesItemId = fieldValue;
                    }
                }
                catch {
                    // Item doesn't exist or couldn't be loaded
                }
            }
            // If both field is filled and item exists, nothing to do
            if (fieldHasValue && standardValuesItemExists) {
                toast.info("Standard Values already exists for this template");
                return;
            }
            // Create Standard Values item if it doesn't exist
            if (!standardValuesItemExists) {
                const createdItem = await context.editContext.operations.createItem(item.descriptor, item.id, // Standard Values items use the parent item ID as their template
                "__Standard Values");
                if (!createdItem) {
                    toast.error("Failed to create Standard Values item");
                    return;
                }
                standardValuesItemId = createdItem.id;
                toast.success("Standard Values item created");
            }
            // Set the field value if it's not already set
            if (!fieldHasValue && standardValuesItemId) {
                await context.editContext.operations.editField({
                    field: standardValuesField.descriptor,
                    value: standardValuesItemId,
                    rawValue: standardValuesItemId,
                    refresh: "immediate",
                });
                toast.success("Standard Values field updated");
            }
            // Refresh the item to show changes
            await context.editContext.itemsRepository.refreshItems([item.descriptor], {
                properties: true,
                children: true,
            });
            context.editContext.requestRefresh("immediate");
        }
        catch (error) {
            toast.error(error instanceof Error
                ? error.message
                : "Failed to add Standard Values");
        }
    },
};
export const publishRestrictionsCommand = {
    id: "publishRestrictions",
    label: "Publish Restrictions...",
    icon: _jsx(RefreshCw, { strokeWidth: 1 }),
    visible: (context) => {
        return !!context.data?.items && context.data.items.length === 1;
    },
    disabled: (context) => {
        return (!context.data?.items ||
            context.data.items.length !== 1 ||
            !context.data.items[0]?.canWriteItem ||
            !context.data.items[0]?.canWriteLanguage ||
            false);
    },
    execute: async (context) => {
        const item = context.data?.items?.[0];
        if (!item)
            return;
        await context.openDialog(PublishRestrictionsDialog, { item });
    },
};
export const publishItemCommand = {
    id: "publishItem",
    label: "Publish Item...",
    icon: _jsx(CheckCircle2, { strokeWidth: 1 }),
    visible: (context) => {
        return !!context.data?.items && context.data.items.length === 1;
    },
    disabled: (context) => {
        return (!context.data?.items ||
            context.data.items.length !== 1 ||
            !context.data.items[0]?.canWriteItem ||
            !context.data.items[0]?.canWriteLanguage ||
            false);
    },
    execute: async (context) => {
        const item = context.data?.items?.[0];
        if (!item)
            return;
        await context.openDialog(PublishItemDialog, { item });
    },
};
export const reviewItemsCommand = {
    id: "reviewItems",
    label: "Review Items",
    icon: _jsx(ClipboardCheck, { strokeWidth: 1 }),
    disabled: (context) => !context.data?.items || context.data.items.length === 0 || false,
    execute: async (context) => {
        const items = context.data?.items;
        if (!items || items.length === 0)
            return;
        const reviewItems = items.map((item) => ({
            id: item.id,
            language: item.language ||
                context.editContext.currentItemDescriptor?.language ||
                "en",
            version: item.version || 0,
            database: item.descriptor?.database,
        }));
        await context.openDialog(CreateReviewDialogWrapper, { initialItems: reviewItems });
    },
};
//# sourceMappingURL=itemCommands.js.map