package ocelot.desktop.node

import ocelot.desktop.color.Color
import ocelot.desktop.geometry.Size2D
import ocelot.desktop.graphics.{Graphics, IconSource}
import ocelot.desktop.node.Node.Size
import ocelot.desktop.ui.event.handlers.{HoverHandler, MouseHandler}
import ocelot.desktop.ui.event.{ClickEvent, HoverEvent, MouseEvent}
import ocelot.desktop.ui.widget.Widget
import ocelot.desktop.ui.widget.tooltip.LabelTooltip
import ocelot.desktop.util.{Spritesheet, TierColor}

class NodeTypeWidget(val nodeType: NodeType) extends Widget with MouseHandler with HoverHandler {
  override def minimumSize: Size2D = Size2D(Size, Size)
  override def maximumSize: Size2D = minimumSize

  size = maximumSize

  def onClick(): Unit = {}

  override protected def receiveClickEvents: Boolean = true

  eventHandlers += {
    case ClickEvent(MouseEvent.Button.Left, _) => onClick()
    case HoverEvent(state) =>
      if (state == HoverEvent.State.Enter) onHoverEnter()
      else onHoverLeave()
  }

  private val labelTooltip = new LabelTooltip(nodeType.name)

  def onHoverEnter(): Unit =
    root.get.tooltipPool.addTooltip(labelTooltip)

  def onHoverLeave(): Unit =
    root.get.tooltipPool.closeTooltip(labelTooltip)

  override def draw(g: Graphics): Unit = {
    val size = Spritesheet.spriteSize(nodeType.icon) * 4

    g.sprite(
      nodeType.icon,
      position.x + Size / 2 - size.width / 2,
      position.y + Size / 2 - size.height / 2,
      size.width,
      size.height,
      nodeType.tier.map(TierColor.get).getOrElse(Color.White),
    )
  }

  override def update(): Unit = {
    super.update()
    if (mouseOver) {
      root.get.statusBar.addMouseEntry(IconSource.Icons.LMB, "Add node")
    }
  }
}
