package ocelot.desktop.ui.widget.contextmenu

import ocelot.desktop.ColorScheme
import ocelot.desktop.color.Color
import ocelot.desktop.geometry.Vector2D
import ocelot.desktop.graphics.Graphics
import ocelot.desktop.ui.UiHandler
import ocelot.desktop.ui.event.HoverEvent

class ContextMenuSubmenu(
  label: String,
  icon: Option[ContextMenuIcon] = None,
  onClick: () => Unit = () => {},
) extends ContextMenuEntry(
      label + "  ",
      icon,
      onClick,
    ) {
  private val parentEntry = this

  private val submenu = new ContextMenu {
    override def update(): Unit = {
      super.update()
      if (
        !isClosing && !bounds.inflated(4).contains(UiHandler.mousePosition)
        && !parentEntry.mouseOver
      ) close()
    }
  }

  def addEntry(entry: ContextMenuEntry): Unit = {
    submenu.addEntry(entry)
  }

  def addSeparator(): Unit = {
    submenu.addSeparator()
  }

  override def clicked(): Unit = {
    if (onClick != null) super.clicked()
  }

  override def leave(): Unit = {
    if (submenu.isClosed) super.leave()
  }

  override def update(): Unit = {
    if (!mouseOver && submenu.isClosed) super.leave()
    super.update()
  }

  override def draw(g: Graphics): Unit = {
    super.draw(g)
    g.background = Color.Transparent
    g.foreground = ColorScheme("ContextMenuText").withAlpha(textAlpha.value)
    g.text(position.x + width - 24, position.y + size.height / 2 - 8, ">")
  }

  eventHandlers += {
    case HoverEvent(HoverEvent.State.Enter) if !isGhost =>
      contextMenus.open(submenu, position + Vector2D(width, -4),
        position.x, position.y + height + 4, isSubmenu = true)
  }
}
