package ocelot.desktop.ui.widget

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
import ocelot.desktop.ui.event.handlers.{HoverHandler, MouseHandler}
import ocelot.desktop.ui.event.{ClickEvent, HoverEvent, MouseEvent}
import ocelot.desktop.util.animation.ColorAnimation

class MenuBarButton(label: String, handler: () => Unit = () => {}) extends Widget with MouseHandler with HoverHandler {

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

  children :+= new PaddingBox(
    new Label {
      override def text: String = label
      override def color: Color = ColorScheme("TitleBarButtonForeground")
      override def maximumSize: Size2D = minimumSize
    },
    Padding2D(left = 8, right = 8, top = 1, bottom = 1),
  )

  override protected def receiveClickEvents: Boolean = true

  def onClick(): Unit = handler()

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

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

  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)
    drawChildren(g)
  }

  protected def clickSoundSource: ClickSoundSourceFactory = SoundSource.InterfaceClick
}
