
import { __decorate, __param } from '../../../../../../../external/tslib/tslib.es6.js';
import { localize } from '../../../../nls.js';
import { KeyCode } from '../../../../base/common/keyCodes.js';
import { $ as $$1, append, EventType, addDisposableListener } from '../../../../base/browser/dom.js';
import { StandardKeyboardEvent } from '../../../../base/browser/keyboardEvent.js';
import { SelectBox, SeparatorSelectOption } from '../../../../base/browser/ui/selectBox/selectBox.js';
import { IConfigurationService } from '../../../../platform/configuration/common/configuration.service.js';
import { ICommandService } from '../../../../platform/commands/common/commands.service.js';
import { State } from '../common/debug.js';
import { IDebugService } from '../common/debug.service.js';
import { ThemeIcon } from '../../../../base/common/themables.js';
import { asCssVariable } from '../../../../platform/theme/common/colorUtils.js';
import '../../../../platform/theme/common/colors/baseColors.js';
import '../../../../platform/theme/common/colors/chartsColors.js';
import '../../../../platform/theme/common/colors/editorColors.js';
import { selectBorder, selectBackground } from '../../../../platform/theme/common/colors/inputColors.js';
import '../../../../platform/theme/common/colors/listColors.js';
import '../../../../platform/theme/common/colors/menuColors.js';
import '../../../../platform/theme/common/colors/minimapColors.js';
import '../../../../platform/theme/common/colors/miscColors.js';
import '../../../../platform/theme/common/colors/quickpickColors.js';
import '../../../../platform/theme/common/colors/searchColors.js';
import { IContextViewService } from '../../../../platform/contextview/browser/contextView.service.js';
import { WorkbenchState } from '../../../../platform/workspace/common/workspace.js';
import { IWorkspaceContextService } from '../../../../platform/workspace/common/workspace.service.js';
import { dispose } from '../../../../base/common/lifecycle.js';
import { ADD_CONFIGURATION_ID } from './debugCommands.js';
import { BaseActionViewItem, SelectActionViewItem } from '../../../../base/browser/ui/actionbar/actionViewItems.js';
import { debugStart } from './debugIcons.js';
import { IKeybindingService } from '../../../../platform/keybinding/common/keybinding.service.js';
import { defaultSelectBoxStyles } from '../../../../platform/theme/browser/defaultStyles.js';
import { getDefaultHoverDelegate } from '../../../../base/browser/ui/hover/hoverDelegateFactory.js';
import { IHoverService } from '../../../../platform/hover/browser/hover.service.js';
import { AccessibilityVerbositySettingId } from '../../accessibility/browser/accessibilityConfiguration.js';
import { AccessibilityCommandId } from '../../accessibility/common/accessibilityCommands.js';
import { IContextKeyService } from '../../../../platform/contextkey/common/contextkey.service.js';
import { hasNativeContextMenu } from '../../../../platform/window/common/window.js';
import { Gesture, EventType as EventType$1 } from '../../../../base/browser/touch.js';

const $ = $$1;
let StartDebugActionViewItem = class StartDebugActionViewItem extends BaseActionViewItem {
    constructor(
        context,
        action,
        options,
        debugService,
        configurationService,
        commandService,
        contextService,
        contextViewService,
        keybindingService,
        hoverService,
        contextKeyService
    ) {
        super(context, action, options);
        this.context = context;
        this.debugService = debugService;
        this.configurationService = configurationService;
        this.commandService = commandService;
        this.contextService = contextService;
        this.keybindingService = keybindingService;
        this.hoverService = hoverService;
        this.contextKeyService = contextKeyService;
        this.debugOptions = [];
        this.selected = 0;
        this.providers = [];
        this.toDispose = [];
        this.selectBox = ( new SelectBox([], -1, contextViewService, defaultSelectBoxStyles, {
            ariaLabel: ( localize(8212, "Debug Launch Configurations")),
            useCustomDrawn: !hasNativeContextMenu(this.configurationService)
        }));
        this.selectBox.setFocusable(false);
        this.toDispose.push(this.selectBox);
        this.registerListeners();
    }
    registerListeners() {
        this.toDispose.push(this.configurationService.onDidChangeConfiguration(e => {
            if (e.affectsConfiguration("launch")) {
                this.updateOptions();
            }
        }));
        this.toDispose.push(
            this.debugService.getConfigurationManager().onDidSelectConfiguration(() => {
                this.updateOptions();
            })
        );
    }
    render(container) {
        this.container = container;
        container.classList.add("start-debug-action-item");
        this.start = append(container, $(ThemeIcon.asCSSSelector(debugStart)));
        const title = this.keybindingService.appendKeybinding(this.action.label, this.action.id);
        this.toDispose.push(
            this.hoverService.setupManagedHover(getDefaultHoverDelegate("mouse"), this.start, title)
        );
        this.start.setAttribute("role", "button");
        this._setAriaLabel(title);
        this._register(Gesture.addTarget(this.start));
        for (const event of [EventType.CLICK, EventType$1.Tap]) {
            this.toDispose.push(addDisposableListener(this.start, event, () => {
                this.start.blur();
                if (this.debugService.state !== State.Initializing) {
                    this.actionRunner.run(this.action, this.context);
                }
            }));
        }
        this.toDispose.push(addDisposableListener(this.start, EventType.MOUSE_DOWN, e => {
            if (this.action.enabled && e.button === 0) {
                this.start.classList.add("active");
            }
        }));
        this.toDispose.push(addDisposableListener(this.start, EventType.MOUSE_UP, () => {
            this.start.classList.remove("active");
        }));
        this.toDispose.push(addDisposableListener(this.start, EventType.MOUSE_OUT, () => {
            this.start.classList.remove("active");
        }));
        this.toDispose.push(addDisposableListener(this.start, EventType.KEY_DOWN, e => {
            const event = ( new StandardKeyboardEvent(e));
            if (event.equals(KeyCode.RightArrow)) {
                this.start.tabIndex = -1;
                this.selectBox.focus();
                event.stopPropagation();
            }
        }));
        this.toDispose.push(this.selectBox.onDidSelect(async e => {
            const target = this.debugOptions[e.index];
            const shouldBeSelected = target.handler ? await target.handler() : false;
            if (shouldBeSelected) {
                this.selected = e.index;
            } else {
                this.selectBox.select(this.selected);
            }
        }));
        const selectBoxContainer = $(".configuration");
        this.selectBox.render(append(container, selectBoxContainer));
        this.toDispose.push(
            addDisposableListener(selectBoxContainer, EventType.KEY_DOWN, e => {
                const event = ( new StandardKeyboardEvent(e));
                if (event.equals(KeyCode.LeftArrow)) {
                    this.selectBox.setFocusable(false);
                    this.start.tabIndex = 0;
                    this.start.focus();
                    event.stopPropagation();
                    event.preventDefault();
                }
            })
        );
        this.container.style.border = `1px solid ${asCssVariable(selectBorder)}`;
        selectBoxContainer.style.borderLeft = `1px solid ${asCssVariable(selectBorder)}`;
        this.container.style.backgroundColor = asCssVariable(selectBackground);
        const configManager = this.debugService.getConfigurationManager();
        const updateDynamicConfigs = () => configManager.getDynamicProviders().then(providers => {
            if (providers.length !== this.providers.length) {
                this.providers = providers;
                this.updateOptions();
            }
        });
        this.toDispose.push(configManager.onDidChangeConfigurationProviders(updateDynamicConfigs));
        updateDynamicConfigs();
        this.updateOptions();
    }
    setActionContext(context) {
        this.context = context;
    }
    isEnabled() {
        return true;
    }
    focus(fromRight) {
        if (fromRight) {
            this.selectBox.focus();
        } else {
            this.start.tabIndex = 0;
            this.start.focus();
        }
    }
    blur() {
        this.start.tabIndex = -1;
        this.selectBox.blur();
        this.container.blur();
    }
    setFocusable(focusable) {
        if (focusable) {
            this.start.tabIndex = 0;
        } else {
            this.start.tabIndex = -1;
            this.selectBox.setFocusable(false);
        }
    }
    dispose() {
        this.toDispose = dispose(this.toDispose);
        super.dispose();
    }
    updateOptions() {
        this.selected = 0;
        this.debugOptions = [];
        const manager = this.debugService.getConfigurationManager();
        const inWorkspace = this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE;
        let lastGroup;
        const disabledIdxs = [];
        const separatorIdxs = [];
        manager.getAllConfigurations().forEach((
            {
                launch,
                name,
                presentation
            }
        ) => {
            if (lastGroup !== presentation?.group) {
                lastGroup = presentation?.group;
                if (this.debugOptions.length) {
                    this.debugOptions.push({
                        label: SeparatorSelectOption.text,
                        handler: () => Promise.resolve(false)
                    });
                    disabledIdxs.push(this.debugOptions.length - 1);
                    separatorIdxs.push(this.debugOptions.length - 1);
                }
            }
            if (name === manager.selectedConfiguration.name && launch === manager.selectedConfiguration.launch) {
                this.selected = this.debugOptions.length;
            }
            const label = inWorkspace ? `${name} (${launch.name})` : name;
            this.debugOptions.push({
                label,
                handler: async () => {
                    await manager.selectConfiguration(launch, name);
                    return true;
                }
            });
        });
        manager.getRecentDynamicConfigurations().slice(0, 3).forEach((
            {
                name,
                type
            }
        ) => {
            if (type === manager.selectedConfiguration.type && manager.selectedConfiguration.name === name) {
                this.selected = this.debugOptions.length;
            }
            this.debugOptions.push({
                label: name,
                handler: async () => {
                    await manager.selectConfiguration(undefined, name, undefined, {
                        type
                    });
                    return true;
                }
            });
        });
        if (this.debugOptions.length === 0) {
            this.debugOptions.push({
                label: ( localize(8213, "No Configurations")),
                handler: async () => false
            });
        }
        this.debugOptions.push({
            label: SeparatorSelectOption.text,
            handler: () => Promise.resolve(false)
        });
        disabledIdxs.push(this.debugOptions.length - 1);
        separatorIdxs.push(this.debugOptions.length - 1);
        this.providers.forEach(p => {
            this.debugOptions.push({
                label: `${p.label}...`,
                handler: async () => {
                    const picked = await p.pick();
                    if (picked) {
                        await manager.selectConfiguration(picked.launch, picked.config.name, picked.config, {
                            type: p.type
                        });
                        return true;
                    }
                    return false;
                }
            });
        });
        manager.getLaunches().filter(l => !l.hidden).forEach(l => {
            const label = inWorkspace ? ( localize(8214, "Add Config ({0})...", l.name)) : ( localize(8215, "Add Configuration..."));
            this.debugOptions.push({
                label,
                handler: async () => {
                    await this.commandService.executeCommand(ADD_CONFIGURATION_ID, ( l.uri.toString()));
                    return false;
                }
            });
        });
        this.selectBox.setOptions(( this.debugOptions.map((data, index) => ({
            text: data.label,
            isDisabled: disabledIdxs.indexOf(index) !== -1,
            isSeparator: separatorIdxs.indexOf(index) !== -1
        }))), this.selected);
    }
    _setAriaLabel(title) {
        let ariaLabel = title;
        let keybinding;
        const verbose = this.configurationService.getValue(AccessibilityVerbositySettingId.Debug);
        if (verbose) {
            keybinding = this.keybindingService.lookupKeybinding(AccessibilityCommandId.OpenAccessibilityHelp, this.contextKeyService)?.getLabel() ?? undefined;
        }
        if (keybinding) {
            ariaLabel = ( localize(8216, "{0}, use ({1}) for accessibility help", ariaLabel, keybinding));
        } else {
            ariaLabel = ( localize(
                8217,
                "{0}, run the command Open Accessibility Help which is currently not triggerable via keybinding.",
                ariaLabel
            ));
        }
        this.start.ariaLabel = ariaLabel;
    }
};
StartDebugActionViewItem = ( __decorate([( __param(3, IDebugService)), ( __param(4, IConfigurationService)), ( __param(5, ICommandService)), ( __param(6, IWorkspaceContextService)), ( __param(7, IContextViewService)), ( __param(8, IKeybindingService)), ( __param(9, IHoverService)), ( __param(10, IContextKeyService))], StartDebugActionViewItem));
let FocusSessionActionViewItem = class FocusSessionActionViewItem extends SelectActionViewItem {
    constructor(action, session, debugService, contextViewService, configurationService) {
        super(null, action, [], -1, contextViewService, defaultSelectBoxStyles, {
            ariaLabel: ( localize(8218, "Debug Session")),
            useCustomDrawn: !hasNativeContextMenu(configurationService)
        });
        this.debugService = debugService;
        this.configurationService = configurationService;
        this._register(this.debugService.getViewModel().onDidFocusSession(() => {
            const session = this.getSelectedSession();
            if (session) {
                const index = this.getSessions().indexOf(session);
                this.select(index);
            }
        }));
        this._register(this.debugService.onDidNewSession(session => {
            const sessionListeners = [];
            sessionListeners.push(session.onDidChangeName(() => this.update()));
            sessionListeners.push(session.onDidEndAdapter(() => dispose(sessionListeners)));
            this.update();
        }));
        this.getSessions().forEach(session => {
            const sessionListeners = [];
            sessionListeners.push(session.onDidChangeName(() => this.update()));
            sessionListeners.push(session.onDidEndAdapter(() => dispose(sessionListeners)));
        });
        this._register(this.debugService.onDidEndSession(() => this.update()));
        const selectedSession = session ? this.mapFocusedSessionToSelected(session) : undefined;
        this.update(selectedSession);
    }
    getActionContext(_, index) {
        return this.getSessions()[index];
    }
    update(session) {
        if (!session) {
            session = this.getSelectedSession();
        }
        const sessions = this.getSessions();
        const names = ( sessions.map(s => {
            const label = s.getLabel();
            if (s.parentSession) {
                return `\u00A0\u00A0${label}`;
            }
            return label;
        }));
        this.setOptions(( names.map(data => ({
            text: data
        }))), session ? sessions.indexOf(session) : undefined);
    }
    getSelectedSession() {
        const session = this.debugService.getViewModel().focusedSession;
        return session ? this.mapFocusedSessionToSelected(session) : undefined;
    }
    getSessions() {
        const showSubSessions = this.configurationService.getValue("debug").showSubSessionsInToolBar;
        const sessions = this.debugService.getModel().getSessions();
        return showSubSessions ? sessions : sessions.filter(s => !s.parentSession);
    }
    mapFocusedSessionToSelected(focusedSession) {
        const showSubSessions = this.configurationService.getValue("debug").showSubSessionsInToolBar;
        while (focusedSession.parentSession && !showSubSessions) {
            focusedSession = focusedSession.parentSession;
        }
        return focusedSession;
    }
};
FocusSessionActionViewItem = ( __decorate([( __param(2, IDebugService)), ( __param(3, IContextViewService)), ( __param(4, IConfigurationService))], FocusSessionActionViewItem));

export { FocusSessionActionViewItem, StartDebugActionViewItem };
