package ocelot.desktop.ui.widget.traits

import ocelot.desktop.color.Color
import ocelot.desktop.geometry.Rect2D
import ocelot.desktop.graphics.Graphics
import ocelot.desktop.ui.Const.{SlotHighlightAlpha, SlotHighlightAnimationSpeedEnter, SlotHighlightAnimationSpeedLeave}
import ocelot.desktop.ui.event.HoverEvent
import ocelot.desktop.ui.event.handlers.HoverHandler
import ocelot.desktop.ui.widget.{Updatable, Widget}
import ocelot.desktop.util.animation.ValueAnimation

trait HoverHighlight extends Widget with HoverHandler with Updatable {
  private val highlightAlpha = new ValueAnimation(0f)

  eventHandlers += {
    case HoverEvent(HoverEvent.State.Enter) =>
      highlightAlpha.speed = SlotHighlightAnimationSpeedEnter
      highlightAlpha.goto(SlotHighlightAlpha)

    case HoverEvent(HoverEvent.State.Leave) =>
      highlightAlpha.speed = SlotHighlightAnimationSpeedLeave
      highlightAlpha.goto(0f)
  }

  protected def highlightBounds: Rect2D = bounds.inflated(-2)

  override def draw(g: Graphics): Unit = {
    super.draw(g)
    drawHighlight(g)
  }

  protected def drawHighlight(g: Graphics): Unit = {
    if (highlightAlpha.value > 0.005f) {
      g.rect(highlightBounds, Color.White.mapA(_ => highlightAlpha.value))
    }
  }

  override def update(): Unit = {
    super.update()
    highlightAlpha.update()
  }
}
