package ocelot.desktop.ui.widget.modal

import ocelot.desktop.graphics.Graphics
import ocelot.desktop.ui.UiHandler
import ocelot.desktop.ui.event.KeyEvent
import ocelot.desktop.ui.widget.Widget
import ocelot.desktop.util.DrawUtils
import ocelot.desktop.util.animation.UnitAnimation
import org.lwjgl.input.Keyboard

abstract class ModalDialog(val autoClose: Boolean = true) extends Widget {
  protected val openCloseAnimation: UnitAnimation = UnitAnimation.easeInOutQuad(0.13f)

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

  def open(): Unit = {
    openCloseAnimation.goUp()
  }

  def close(): Unit = {
    openCloseAnimation.goDown()
  }

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

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

  override def update(): Unit = {
    super.update()
    openCloseAnimation.update()
  }

  override def draw(g: Graphics): Unit = {
    if (openCloseAnimation.value < 0.999)
      g.beginGroupAlpha()

    drawInner(g)

    if (openCloseAnimation.value < 0.999)
      g.endGroupAlpha(openCloseAnimation.value)
  }

  protected def drawInner(g: Graphics): Unit = {
    DrawUtils.windowWithShadow(g, position.x, position.y, size.width, size.height, 1f, 0.5f)
    drawChildren(g)
  }

  def show(): Unit = {
    UiHandler.root.modalDialogPool.pushDialog(this)
  }
}
