// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.wm.impl.customFrameDecorations.header.toolbar

import com.intellij.icons.AllIcons
import com.intellij.ide.IdeBundle
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.actionSystem.impl.PresentationFactory
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.Disposer
import com.intellij.ui.IconManager
import com.intellij.util.ui.JBUI
import org.jetbrains.annotations.ApiStatus
import java.awt.Dimension
import javax.swing.JComponent

@ApiStatus.Internal
internal class MainMenuButton {

  private val menuAction = ShowMenuAction()

  val button: ActionButton = createMenuButton(menuAction)
  val menuShortcutHandler = MainMenuMnemonicHandler(menuAction)

  private inner class ShowMenuAction : DumbAwareAction() {

    private val icon = IconManager.getInstance().getIcon("expui/general/windowsMenu@20x20.svg", AllIcons::class.java)

    override fun update(e: AnActionEvent) {
      e.presentation.icon = icon
      e.presentation.text = IdeBundle.message("main.toolbar.menu.button")
    }

    override fun actionPerformed(e: AnActionEvent) = createPopup(e.dataContext).showUnderneathOf(button)

    private fun createPopup(context: DataContext): JBPopup {
      val mainMenu = ActionManager.getInstance().getAction(IdeActions.GROUP_MAIN_MENU) as ActionGroup
      return JBPopupFactory.getInstance()
        .createActionGroupPopup(null, mainMenu, context, JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, true,
                                ActionPlaces.MAIN_MENU_IN_POPUP)
        .apply { setShowSubmenuOnHover(true) }
        .apply { setMinimumSize(Dimension(JBUI.CurrentTheme.CustomFrameDecorations.menuPopupMinWidth(), 0)) }
    }
  }

  companion object {
    private fun createMenuButton(action: AnAction): ActionButton {
      return ActionButton(action, PresentationFactory().getPresentation(action),
                          ActionPlaces.MAIN_MENU_IN_POPUP, Dimension(40, 40))
        .apply { setLook(HeaderToolbarButtonLook()) }
    }
  }
}

class MainMenuMnemonicHandler(val action: AnAction) : Disposable {

  private var disposable: Disposable? = null

  fun registerShortcuts(component: JComponent) {
    if (disposable == null) disposable = Disposer.newDisposable()

    val shortcutSet = ActionUtil.getShortcutSet("MainMenuButton.ShowMenu")
    action.registerCustomShortcutSet(shortcutSet, component, disposable)
  }

  fun unregisterShortcuts() {
    disposable?.let { Disposer.dispose(it) }
  }

  override fun dispose() = unregisterShortcuts()
}
