package ocelot.desktop.ui.widget.verticalmenu

import ocelot.desktop.ColorScheme
import ocelot.desktop.audio.{ClickSoundSourceFactory, SoundSource}
import ocelot.desktop.color.Color
import ocelot.desktop.geometry.{Padding2D, Size2D}
import ocelot.desktop.graphics.{Graphics, IconSource}
import ocelot.desktop.ui.event.handlers.{HoverHandler, MouseHandler}
import ocelot.desktop.ui.event.{ClickEvent, HoverEvent, MouseEvent}
import ocelot.desktop.ui.layout.LinearLayout
import ocelot.desktop.ui.widget._
import ocelot.desktop.util.Orientation
import ocelot.desktop.util.animation.ColorAnimation

class VerticalMenuButton(icon: IconSource, label: String, handler: VerticalMenuButton => Unit = _ => {})
    extends Widget with MouseHandler with HoverHandler {

  val colorAnimation: ColorAnimation = new ColorAnimation(ColorScheme("VerticalMenuBackground"), 0.6f)

  var selected = false

  children :+= new PaddingBox(
    new Widget {
      override val layout = new LinearLayout(this, orientation = Orientation.Horizontal)

      children :+= new PaddingBox(
        new Icon(icon, color = ColorScheme("VerticalMenuEntryIcon")),
        Padding2D(right = 8),
      )

      children :+= new Label {
        override def text: String = label
        override def color: Color = ColorScheme("VerticalMenuEntryForeground")
        override def maximumSize: Size2D = Size2D(Float.PositiveInfinity, 16)
      }
    },
    Padding2D(left = 8, right = 24, top = 8, bottom = 8),
  )

  override protected def receiveClickEvents: Boolean = true

  def onClick(): Unit = handler(this)

  def onMouseEnter(): Unit = colorAnimation.goto(ColorScheme("VerticalMenuEntryActive"))

  def onMouseLeave(): Unit = colorAnimation.goto(ColorScheme("VerticalMenuBackground"))

  eventHandlers += {
    case MouseEvent(MouseEvent.State.Pressed, MouseEvent.Button.Left) =>
      clickSoundSource.press.play()

    case ClickEvent(MouseEvent.Button.Left, _) =>
      onClick()
      clickSoundSource.release.play()

    case HoverEvent(HoverEvent.State.Enter) =>
      onMouseEnter()

    case HoverEvent(HoverEvent.State.Leave) =>
      onMouseLeave()
  }

  override def draw(g: Graphics): Unit = {
    colorAnimation.update()
    g.rect(bounds, colorAnimation.color)
    g.rect(bounds.x + bounds.w - 2f, bounds.y, 2f, bounds.h, ColorScheme("VerticalMenuBorder"))
    if (selected) g.sprite(IconSource.TabArrow, bounds.x + bounds.w - 8f, bounds.y + bounds.h / 2f - 7f, 8, 14)
    drawChildren(g)
  }

  protected def clickSoundSource: ClickSoundSourceFactory = SoundSource.InterfaceClick
}
