import { __decorate, __param } from '../../../../../../external/tslib/tslib.es6.js';
import { addDisposableListener, getWindow } from '../../../base/browser/dom.js';
import { StandardMouseEvent } from '../../../base/browser/mouseEvent.js';
import { ToolBar } from '../../../base/browser/ui/toolbar/toolbar.js';
import { Separator, toAction } from '../../../base/common/actions.js';
import { coalesceInPlace } from '../../../base/common/arrays.js';
import { intersection } from '../../../base/common/collections.js';
import { BugIndicatingError } from '../../../base/common/errors.js';
import { Emitter } from '../../../base/common/event.js';
import { Iterable } from '../../../base/common/iterator.js';
import { DisposableStore } from '../../../base/common/lifecycle.js';
import { localizeWithPath } from '../../../nls.js';
import { createAndFillInActionBarActions } from './menuEntryActionViewItem.js';
import { MenuItemAction, SubmenuItemAction } from '../common/actions.js';
import { IMenuService } from '../common/actions.service.js';
import { IContextKeyService } from '../../contextkey/common/contextkey.service.js';
import { IContextMenuService } from '../../contextview/browser/contextView.service.js';
import { IKeybindingService } from '../../keybinding/common/keybinding.service.js';
import { ITelemetryService } from '../../telemetry/common/telemetry.service.js';
const _moduleId = "vs/platform/actions/browser/toolbar";
let WorkbenchToolBar = class WorkbenchToolBar extends ToolBar {
    constructor(container, _options, _menuService, _contextKeyService, _contextMenuService, keybindingService, telemetryService) {
        super(container, _contextMenuService, {
            getKeyBinding: (action) => keybindingService.lookupKeybinding(action.id) ?? undefined,
            ..._options,
            allowContextMenu: true,
            skipTelemetry: typeof _options?.telemetrySource === 'string',
        });
        this._options = _options;
        this._menuService = _menuService;
        this._contextKeyService = _contextKeyService;
        this._contextMenuService = _contextMenuService;
        this._sessionDisposables = this._store.add(( (new DisposableStore())));
        const telemetrySource = _options?.telemetrySource;
        if (telemetrySource) {
            this._store.add(this.actionBar.onDidRun(e => telemetryService.publicLog2('workbenchActionExecuted', { id: e.action.id, from: telemetrySource })));
        }
    }
    setActions(_primary, _secondary = [], menuIds) {
        this._sessionDisposables.clear();
        const primary = _primary.slice();
        const secondary = _secondary.slice();
        const toggleActions = [];
        let toggleActionsCheckedCount = 0;
        const extraSecondary = [];
        let someAreHidden = false;
        if (this._options?.hiddenItemStrategy !== -1 ) {
            for (let i = 0; i < primary.length; i++) {
                const action = primary[i];
                if (!(action instanceof MenuItemAction) && !(action instanceof SubmenuItemAction)) {
                    continue;
                }
                if (!action.hideActions) {
                    continue;
                }
                toggleActions.push(action.hideActions.toggle);
                if (action.hideActions.toggle.checked) {
                    toggleActionsCheckedCount++;
                }
                if (action.hideActions.isHidden) {
                    someAreHidden = true;
                    primary[i] = undefined;
                    if (this._options?.hiddenItemStrategy !== 0 ) {
                        extraSecondary[i] = action;
                    }
                }
            }
        }
        if (this._options?.overflowBehavior !== undefined) {
            const exemptedIds = intersection(( (new Set(this._options.overflowBehavior.exempted))), ( (Iterable.map(primary, a => a?.id))));
            const maxItems = this._options.overflowBehavior.maxItems - exemptedIds.size;
            let count = 0;
            for (let i = 0; i < primary.length; i++) {
                const action = primary[i];
                if (!action) {
                    continue;
                }
                count++;
                if (( (exemptedIds.has(action.id)))) {
                    continue;
                }
                if (count >= maxItems) {
                    primary[i] = undefined;
                    extraSecondary[i] = action;
                }
            }
        }
        coalesceInPlace(primary);
        coalesceInPlace(extraSecondary);
        super.setActions(primary, Separator.join(extraSecondary, secondary));
        if (toggleActions.length > 0) {
            this._sessionDisposables.add(addDisposableListener(this.getElement(), 'contextmenu', e => {
                const event = ( (new StandardMouseEvent(getWindow(this.getElement()), e)));
                const action = this.getItemAction(event.target);
                if (!(action)) {
                    return;
                }
                event.preventDefault();
                event.stopPropagation();
                let noHide = false;
                if (toggleActionsCheckedCount === 1 && this._options?.hiddenItemStrategy === 0 ) {
                    noHide = true;
                    for (let i = 0; i < toggleActions.length; i++) {
                        if (toggleActions[i].checked) {
                            toggleActions[i] = toAction({
                                id: action.id,
                                label: action.label,
                                checked: true,
                                enabled: false,
                                run() { }
                            });
                            break;
                        }
                    }
                }
                let hideAction;
                if (!noHide && (action instanceof MenuItemAction || action instanceof SubmenuItemAction)) {
                    if (!action.hideActions) {
                        return;
                    }
                    hideAction = action.hideActions.hide;
                }
                else {
                    hideAction = toAction({
                        id: 'label',
                        label: ( localizeWithPath(_moduleId, 0, "Hide")),
                        enabled: false,
                        run() { }
                    });
                }
                const actions = Separator.join([hideAction], toggleActions);
                if (this._options?.resetMenu && !menuIds) {
                    menuIds = [this._options.resetMenu];
                }
                if (someAreHidden && menuIds) {
                    actions.push(( (new Separator())));
                    actions.push(toAction({
                        id: 'resetThisMenu',
                        label: ( localizeWithPath(_moduleId, 1, "Reset Menu")),
                        run: () => this._menuService.resetHiddenStates(menuIds)
                    }));
                }
                this._contextMenuService.showContextMenu({
                    getAnchor: () => event,
                    getActions: () => actions,
                    menuId: this._options?.contextMenu,
                    menuActionOptions: { renderShortTitle: true, ...this._options?.menuOptions },
                    skipTelemetry: typeof this._options?.telemetrySource === 'string',
                    contextKeyService: this._contextKeyService,
                });
            }));
        }
    }
};
WorkbenchToolBar = ( (__decorate([
    ( (__param(2, IMenuService))),
    ( (__param(3, IContextKeyService))),
    ( (__param(4, IContextMenuService))),
    ( (__param(5, IKeybindingService))),
    ( (__param(6, ITelemetryService)))
], WorkbenchToolBar)));
let MenuWorkbenchToolBar = class MenuWorkbenchToolBar extends WorkbenchToolBar {
    constructor(container, menuId, options, menuService, contextKeyService, contextMenuService, keybindingService, telemetryService) {
        super(container, { resetMenu: menuId, ...options }, menuService, contextKeyService, contextMenuService, keybindingService, telemetryService);
        this._onDidChangeMenuItems = this._store.add(( (new Emitter())));
        this.onDidChangeMenuItems = this._onDidChangeMenuItems.event;
        const menu = this._store.add(menuService.createMenu(menuId, contextKeyService, { emitEventsForSubmenuChanges: true }));
        const updateToolbar = () => {
            const primary = [];
            const secondary = [];
            createAndFillInActionBarActions(menu, options?.menuOptions, { primary, secondary }, options?.toolbarOptions?.primaryGroup, options?.toolbarOptions?.shouldInlineSubmenu, options?.toolbarOptions?.useSeparatorsInPrimaryActions);
            container.classList.toggle('has-no-actions', primary.length === 0 && secondary.length === 0);
            super.setActions(primary, secondary);
        };
        this._store.add(menu.onDidChange(() => {
            updateToolbar();
            this._onDidChangeMenuItems.fire(this);
        }));
        updateToolbar();
    }
    setActions() {
        throw ( (new BugIndicatingError('This toolbar is populated from a menu.')));
    }
};
MenuWorkbenchToolBar = ( (__decorate([
    ( (__param(3, IMenuService))),
    ( (__param(4, IContextKeyService))),
    ( (__param(5, IContextMenuService))),
    ( (__param(6, IKeybindingService))),
    ( (__param(7, ITelemetryService)))
], MenuWorkbenchToolBar)));
export { MenuWorkbenchToolBar, WorkbenchToolBar };
