import { Codicon } from '../../../../../base/common/codicons.js';
import { KeyMod as KeyMod$1, KeyCode } from '../../../../../base/common/keyCodes.js';
import { DisposableStore } from '../../../../../base/common/lifecycle.js';
import { ThemeIcon } from '../../../../../base/common/themables.js';
import { EditorAction2 } from '../../../../../editor/browser/editorExtensions.js';
import { localize2WithPath, localizeWithPath } from '../../../../../nls.js';
import { registerAction2, Action2, MenuId } from '../../../../../platform/actions/common/actions.js';
import { ContextKeyExpr } from '../../../../../platform/contextkey/common/contextkey.js';
import { IsWindowsContext, IsLinuxContext } from '../../../../../platform/contextkey/common/contextkeys.js';
import { KeybindingWeight } from '../../../../../platform/keybinding/common/keybindingsRegistry.js';
import { IQuickInputService } from '../../../../../platform/quickinput/common/quickInput.service.js';
import { showChatView, CHAT_VIEW_ID } from '../chat.js';
import { IChatWidgetService } from '../chat.service.js';
import { ChatEditorInput } from '../chatEditorInput.js';
import { ChatAgentLocation } from '../../common/chatAgents.js';
import { CONTEXT_CHAT_ENABLED, CONTEXT_IN_CHAT_INPUT, CONTEXT_CHAT_LOCATION, CONTEXT_CHAT_INPUT_CURSOR_AT_TOP, CONTEXT_IN_CHAT_SESSION } from '../../common/chatContextKeys.js';
import { IChatService } from '../../common/chatService.service.js';
import { isRequestVM } from '../../common/chatViewModel.js';
import { IChatWidgetHistoryService } from '../../common/chatWidgetHistoryService.service.js';
import { ACTIVE_GROUP } from '../../../../services/editor/common/editorService.js';
import { IEditorService } from '../../../../services/editor/common/editorService.service.js';
import { IViewsService } from '../../../../services/views/common/viewsService.service.js';
const _moduleId = "vs/workbench/contrib/chat/browser/actions/chatActions";
function isChatViewTitleActionContext(obj) {
    return obj instanceof Object && 'chatView' in obj;
}
const CHAT_CATEGORY = ( localize2WithPath(_moduleId, 0, 'Chat'));
const CHAT_OPEN_ACTION_ID = 'workbench.action.chat.open';
class OpenChatGlobalAction extends Action2 {
    constructor() {
        super({
            id: CHAT_OPEN_ACTION_ID,
            title: ( localize2WithPath(_moduleId, 1, "Open Chat")),
            icon: Codicon.commentDiscussion,
            f1: false,
            category: CHAT_CATEGORY,
            keybinding: {
                weight: KeybindingWeight.WorkbenchContrib,
                primary: KeyMod$1.CtrlCmd | KeyMod$1.Alt | KeyCode.KeyI,
                mac: {
                    primary: KeyMod$1.CtrlCmd | KeyMod$1.WinCtrl | KeyCode.KeyI
                }
            }
        });
    }
    async run(accessor, opts) {
        opts = typeof opts === 'string' ? { query: opts } : opts;
        const chatService = accessor.get(IChatService);
        const chatWidget = await showChatView(accessor.get(IViewsService));
        if (!chatWidget) {
            return;
        }
        if (opts?.previousRequests?.length && chatWidget.viewModel) {
            for (const { request, response } of opts.previousRequests) {
                chatService.addCompleteRequest(chatWidget.viewModel.sessionId, request, undefined, 0, { message: response });
            }
        }
        if (opts?.query) {
            if (opts.isPartialQuery) {
                chatWidget.setInput(opts.query);
            }
            else {
                chatWidget.acceptInput(opts.query);
            }
        }
        chatWidget.focusInput();
    }
}
class ChatHistoryAction extends Action2 {
    constructor() {
        super({
            id: `workbench.action.chat.history`,
            title: ( localize2WithPath(_moduleId, 2, "Show Chats...")),
            menu: {
                id: MenuId.ViewTitle,
                when: ( (ContextKeyExpr.equals('view', CHAT_VIEW_ID))),
                group: 'navigation',
                order: -1
            },
            category: CHAT_CATEGORY,
            icon: Codicon.history,
            f1: true,
            precondition: CONTEXT_CHAT_ENABLED
        });
    }
    async run(accessor) {
        const chatService = accessor.get(IChatService);
        const quickInputService = accessor.get(IQuickInputService);
        const viewsService = accessor.get(IViewsService);
        const editorService = accessor.get(IEditorService);
        const openInEditorButton = {
            iconClass: ThemeIcon.asClassName(Codicon.file),
            tooltip: ( localizeWithPath(_moduleId, 3, "Open in Editor")),
        };
        const deleteButton = {
            iconClass: ThemeIcon.asClassName(Codicon.x),
            tooltip: ( localizeWithPath(_moduleId, 4, "Delete")),
        };
        const getPicks = () => {
            const items = chatService.getHistory();
            return (
                 (items.map((i) => ({
                    label: i.title,
                    chat: i,
                    buttons: [
                        openInEditorButton,
                        deleteButton
                    ]
                })))
            );
        };
        const store = ( (new DisposableStore()));
        const picker = store.add(quickInputService.createQuickPick());
        picker.placeholder = ( localizeWithPath(_moduleId, 5, "Switch to chat"));
        picker.items = getPicks();
        store.add(picker.onDidTriggerItemButton(context => {
            if (context.button === openInEditorButton) {
                editorService.openEditor({ resource: ChatEditorInput.getNewEditorUri(), options: { target: { sessionId: context.item.chat.sessionId }, pinned: true } }, ACTIVE_GROUP);
                picker.hide();
            }
            else if (context.button === deleteButton) {
                chatService.removeHistoryEntry(context.item.chat.sessionId);
                picker.items = getPicks();
            }
        }));
        store.add(picker.onDidAccept(async () => {
            try {
                const item = picker.selectedItems[0];
                const sessionId = item.chat.sessionId;
                const view = await viewsService.openView(CHAT_VIEW_ID);
                view.loadSession(sessionId);
            }
            finally {
                picker.hide();
            }
        }));
        store.add(picker.onDidHide(() => store.dispose()));
        picker.show();
    }
}
class OpenChatEditorAction extends Action2 {
    constructor() {
        super({
            id: `workbench.action.openChat`,
            title: ( localize2WithPath(_moduleId, 6, "Open Editor")),
            f1: true,
            category: CHAT_CATEGORY,
            precondition: CONTEXT_CHAT_ENABLED
        });
    }
    async run(accessor) {
        const editorService = accessor.get(IEditorService);
        await editorService.openEditor({ resource: ChatEditorInput.getNewEditorUri(), options: { pinned: true } });
    }
}
function registerChatActions() {
    registerAction2(OpenChatGlobalAction);
    registerAction2(ChatHistoryAction);
    registerAction2(OpenChatEditorAction);
    registerAction2(class ClearChatInputHistoryAction extends Action2 {
        constructor() {
            super({
                id: 'workbench.action.chat.clearInputHistory',
                title: ( localize2WithPath(_moduleId, 7, "Clear Input History")),
                precondition: CONTEXT_CHAT_ENABLED,
                category: CHAT_CATEGORY,
                f1: true,
            });
        }
        async run(accessor, ...args) {
            const historyService = accessor.get(IChatWidgetHistoryService);
            historyService.clearHistory();
        }
    });
    registerAction2(class ClearChatHistoryAction extends Action2 {
        constructor() {
            super({
                id: 'workbench.action.chat.clearHistory',
                title: ( localize2WithPath(_moduleId, 8, "Clear All Workspace Chats")),
                precondition: CONTEXT_CHAT_ENABLED,
                category: CHAT_CATEGORY,
                f1: true,
            });
        }
        async run(accessor, ...args) {
            const chatService = accessor.get(IChatService);
            chatService.clearAllHistoryEntries();
        }
    });
    registerAction2(class FocusChatAction extends EditorAction2 {
        constructor() {
            super({
                id: 'chat.action.focus',
                title: ( localize2WithPath(_moduleId, 9, 'Focus Chat List')),
                precondition: ( (ContextKeyExpr.and(
                    CONTEXT_IN_CHAT_INPUT,
                     (CONTEXT_CHAT_LOCATION.isEqualTo(ChatAgentLocation.Panel))
                ))),
                category: CHAT_CATEGORY,
                keybinding: [
                    {
                        when: CONTEXT_CHAT_INPUT_CURSOR_AT_TOP,
                        primary: KeyMod$1.CtrlCmd | KeyCode.UpArrow,
                        weight: KeybindingWeight.EditorContrib,
                    },
                    {
                        when: ( (ContextKeyExpr.or(IsWindowsContext, IsLinuxContext))),
                        primary: KeyMod$1.CtrlCmd | KeyCode.UpArrow,
                        weight: KeybindingWeight.EditorContrib,
                    }
                ]
            });
        }
        runEditorCommand(accessor, editor) {
            const editorUri = editor.getModel()?.uri;
            if (editorUri) {
                const widgetService = accessor.get(IChatWidgetService);
                widgetService.getWidgetByInputUri(editorUri)?.focusLastMessage();
            }
        }
    });
    registerAction2(class FocusChatInputAction extends Action2 {
        constructor() {
            super({
                id: 'workbench.action.chat.focusInput',
                title: ( localize2WithPath(_moduleId, 10, "Focus Chat Input")),
                f1: false,
                keybinding: {
                    primary: KeyMod$1.CtrlCmd | KeyCode.DownArrow,
                    weight: KeybindingWeight.WorkbenchContrib,
                    when: ( (ContextKeyExpr.and(CONTEXT_IN_CHAT_SESSION,  (CONTEXT_IN_CHAT_INPUT.negate()))))
                }
            });
        }
        run(accessor, ...args) {
            const widgetService = accessor.get(IChatWidgetService);
            widgetService.lastFocusedWidget?.focusInput();
        }
    });
}
function stringifyItem(item, includeName = true) {
    if (isRequestVM(item)) {
        return (includeName ? `${item.username}: ` : '') + item.messageText;
    }
    else {
        return (includeName ? `${item.username}: ` : '') + item.response.asString();
    }
}
export { CHAT_CATEGORY, CHAT_OPEN_ACTION_ID, isChatViewTitleActionContext, registerChatActions, stringifyItem };
