package ocelot.desktop.ui.widget

import ocelot.desktop.ColorScheme
import ocelot.desktop.audio.SoundSource
import ocelot.desktop.color.Color
import ocelot.desktop.geometry.Size2D
import ocelot.desktop.graphics.Graphics
import ocelot.desktop.ui.event.handlers.{ClickHandler, HoverHandler}
import ocelot.desktop.ui.event.{ClickEvent, HoverEvent, MouseEvent}
import ocelot.desktop.ui.widget.tooltip.Tooltip
import ocelot.desktop.util.DrawUtils

class Button(tooltip: Tooltip = null) extends Widget with ClickHandler with HoverHandler with ClickSoundSource {
  protected def colorScheme: ColorScheme = ColorScheme.General

  def text: String = ""

  def onClick(): Unit = {}

  override def receiveMouseEvents: Boolean = true

  eventHandlers += {
    case ClickEvent(MouseEvent.Button.Left, _) if enabled =>
      onClick()
      clickSoundSource.play()
  }

  if (tooltip != null) {
    eventHandlers += {
      case HoverEvent(HoverEvent.State.Enter) => onHoverEnter()
      case HoverEvent(HoverEvent.State.Leave) => onHoverLeave()
    }
  }

  private def onHoverEnter(): Unit = {
    root.get.tooltipPool.addTooltip(tooltip)
  }

  private def onHoverLeave(): Unit = {
    root.get.tooltipPool.closeTooltip(tooltip)
  }

  override def minimumSize: Size2D = Size2D(24 + text.length * 8, 24)

  override def maximumSize: Size2D = minimumSize

  override def draw(g: Graphics): Unit = {
    val (background, border, foreground) = if (enabled) (
      colorScheme("ButtonBackground"),
      colorScheme("ButtonBorder"),
      colorScheme("ButtonForeground")
    ) else (
      colorScheme("ButtonBackgroundDisabled"),
      colorScheme("ButtonBorderDisabled"),
      colorScheme("ButtonForegroundDisabled")
    )

    g.rect(bounds, background)
    DrawUtils.ring(g, position.x, position.y, width, height, 2, border)

    g.background = Color.Transparent
    g.foreground = foreground
    val textWidth = text.iterator.map(g.font.charWidth(_)).sum
    g.text(position.x + ((width - textWidth) / 2).round, position.y + 4, text)
  }

  override protected def clickSoundSource: SoundSource = SoundSource.InterfaceClick
}
