package ocelot.desktop.ui.widget

import ocelot.desktop.color.{Color, IntColor}
import ocelot.desktop.geometry.{Size2D, Vector2D}
import ocelot.desktop.graphics.{Graphics, IconSource}
import ocelot.desktop.ui.UiHandler
import ocelot.desktop.ui.event.MouseEvent
import totoro.ocelot.brain.util.DyeColor

abstract class Knob(dyeColor: DyeColor = DyeColor.Red) extends Widget {
  def input: Int
  def input_=(v: Int): Unit

  def output: Int

  val color: Color = {
    var hsv = IntColor(dyeColor.rgb).toHSVA
    if (hsv.v > 0.6) hsv = hsv.copy(v = 0.6f)
    hsv.toRGBANorm
  }

  override def minimumSize: Size2D = Size2D(25, 25)
  override def maximumSize: Size2D = minimumSize

  override def receiveMouseEvents: Boolean = true

  private var movePos: Option[Vector2D] = None
  private var startValue: Int = 0

  eventHandlers += {
    case MouseEvent(MouseEvent.State.Pressed, MouseEvent.Button.Left) =>
      val mousePos = UiHandler.mousePosition
      if (bounds.contains(mousePos)) {
        movePos = Some(mousePos)
        startValue = input
      }

    case MouseEvent(MouseEvent.State.Released, MouseEvent.Button.Left) =>
      movePos = None
  }

  override def update(): Unit = {
    super.update()
    if (movePos.isEmpty) return
    val dist = (UiHandler.mousePosition.x - movePos.get.x) / 2f
    input = (startValue + dist.toInt) min 15 max 0
  }

  override def draw(g: Graphics): Unit = {
    g.sprite(IconSource.KnobLimits, position.x, position.y, 25, 25)
    g.save()
    g.translate(position.x + 12.5f, position.y + 12.5f)
    g.rotate(input.toFloat / 15f * 4.71239f - 0.785398f)
    g.sprite(IconSource.Knob, -12.5f, -12.5f, 25, 25, color)
    g.restore()
    g.sprite(IconSource.KnobCenter, position.x, position.y, 25, 25)
    val centerColor = color.toRGBANorm.copy(a = output / 15f)
    g.sprite(IconSource.KnobCenter, position.x - 1, position.y - 1, 27, 27, centerColor)
  }
}
