package ocelot.desktop.ui.widget.tooltip

import ocelot.desktop.color.{Color, RGBAColor}
import ocelot.desktop.geometry.Padding2D
import ocelot.desktop.graphics.Graphics
import ocelot.desktop.ui.event.KeyEvent
import ocelot.desktop.ui.layout.LinearLayout
import ocelot.desktop.ui.widget.{PaddingBox, Widget}
import ocelot.desktop.util.Orientation
import ocelot.desktop.util.animation.UnitAnimation

abstract class Tooltip extends Widget {
  protected val openCloseAnimation: UnitAnimation = UnitAnimation.easeInOutQuad(0.3f)

  val body: Widget = new Widget {
    override val layout = new LinearLayout(this, orientation = Orientation.Vertical)
  }

  def bodyPadding: Padding2D

  children :+= new PaddingBox(body, bodyPadding)

  /** Time before the tooltip will become visible (in seconds) */
  val DelayTime = 0.001f

  eventHandlers += {
    case KeyEvent(KeyEvent.State.Press, _, _) =>
      close()
  }

  def open(instantly: Boolean = false): Unit = {
    if (instantly) openCloseAnimation.jumpUp()
    openCloseAnimation.goUp()
  }

  def close(instantly: Boolean = false): Unit = {
    if (instantly) openCloseAnimation.jumpDown()
    openCloseAnimation.goDown()
  }

  def isClosing: Boolean = {
    openCloseAnimation.direction < 0.0
  }

  def isClosed: Boolean = {
    openCloseAnimation.value < 0.01 && openCloseAnimation.direction <= 0.0
  }

  def getAlpha: Float = openCloseAnimation.value

  override def update(): Unit = {
    super.update()
    openCloseAnimation.update(if (isClosing) 1.0f else 10.0f)
  }

  override def draw(g: Graphics): Unit = {
    if (getAlpha < 0.999) g.beginGroupAlpha()
    drawInner(g)
    if (getAlpha < 0.999) g.endGroupAlpha(getAlpha)
  }

  protected def drawInner(g: Graphics): Unit = {
    g.rect(position.x, position.y, size.width, size.height, Color.Black)
    g.rect(position.x + 5, position.y + 5, size.width, size.height, RGBAColor(20, 20, 20, 100))
    drawChildren(g)
  }
}
