package ocelot.desktop.util.animation

import ocelot.desktop.ui.UiHandler
import ocelot.desktop.util.animation.easing.Easing
import totoro.ocelot.brain.nbt.NBTTagCompound

object UnitAnimation {
  def linear(duration: Float) = new UnitAnimation(duration, Easing.linear)

  def easeInQuad(duration: Float) = new UnitAnimation(duration, Easing.easeInQuad)

  def easeOutQuad(duration: Float) = new UnitAnimation(duration, Easing.easeOutQuad)

  def easeInOutQuad(duration: Float) = new UnitAnimation(duration, Easing.easeInOutQuad)
}

class UnitAnimation(duration: Float, function: Float => Float) {
  var direction: Float = 1
  var time: Float = 0

  def value: Float = function(time)

  def goUp(): Unit = direction = 1
  def jumpUp(): Unit = time = 1
  def isGoingUp: Boolean = direction == 1

  def goDown(): Unit = direction = -1
  def jumpDown(): Unit = time = 0
  def isGoingDown: Boolean = direction == -1

  def reverse(): Unit = direction = -direction

  def update(multiplier: Float = 1.0f): Unit = {
    time += (direction * UiHandler.dt / duration) * multiplier
    time = math.max(0, math.min(1, time))
  }

  def save(nbt: NBTTagCompound, name: String): Unit = {
    val animationNbt = new NBTTagCompound
    animationNbt.setFloat("direction", direction)
    animationNbt.setFloat("time", time)
    nbt.setTag(name, animationNbt)
  }

  def load(nbt: NBTTagCompound, name: String): Unit = {
    if (nbt.hasKey(name)) {
      val animationNbt = nbt.getCompoundTag(name)
      time = animationNbt.getFloat("time")
      direction = animationNbt.getFloat("direction")
    }
  }
}
