package ocelot.desktop.ui.widget.window

import ocelot.desktop.Settings
import ocelot.desktop.graphics.Graphics
import ocelot.desktop.util.DrawUtils
import ocelot.desktop.util.animation.ValueAnimation
import totoro.ocelot.brain.nbt.NBTTagCompound

trait BasicWindow extends Window {
  private val alpha = new ValueAnimation(speed = 7)

  override protected def onOpening(): Window.State.Value = {
    super.onOpening()
    alpha.goto(1)
    Window.State.Opening
  }

  override protected def onClosing(): Window.State.Value = {
    super.onClosing()
    alpha.goto(0)
    Window.State.Closing
  }

  override protected def onFocused(): Unit = {
    super.onFocused()
    alpha.goto(1)
  }

  override protected def onUnfocused(): Unit = {
    super.onUnfocused()
    if (Settings.get.unfocusedWindowHide) {
      close()
    } else {
      alpha.goto(Settings.get.unfocusedWindowTransparency)
    }
  }

  override def save(nbt: NBTTagCompound): Unit = {
    super.save(nbt)
    alpha.save(nbt, "alpha")
  }

  override def load(nbt: NBTTagCompound): Unit = {
    super.load(nbt)
    alpha.load(nbt, "alpha")
  }

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

    alpha.update()

    if (state == Window.State.Closing && alpha.value < 0.001) {
      state = Window.State.Closed
    } else if (state == Window.State.Opening && alpha.value > 0.999) {
      state = Window.State.Open
    }
  }

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

  protected def beginDraw(g: Graphics): Unit = {
    if (alpha.value < 1f)
      g.beginGroupAlpha()
  }

  protected def endDraw(g: Graphics): Unit = {
    if (alpha.value < 1f)
      g.endGroupAlpha(alpha.value)
  }

  override def refresh(): Unit = {
    // currently is only used to update unfocused transparency values (could be extended in the future)
    if (!isFocused) {
      if (Settings.get.unfocusedWindowHide && (isOpen || isOpening)) {
        this.close()
      } else {
        alpha.goto(Settings.get.unfocusedWindowTransparency)
      }
    }
  }
}
