class_name TransitionSingleton extends Control

enum FadeType {
  NONE,
  FADE_IN,
  FADE_OUT
}

signal fadeOutStart
signal fadeOutEnd
signal fadeInStart
signal fadeInEnd
signal fadeUpdate(t:float)

var fadeType:FadeType = FadeType.NONE
var fadeDuration:float = 0.4
var fadeTime:float = 0.0
var inFade = false

func _enter_tree() -> void:
  $Overlay.visible = false

func _process(delta: float) -> void:
  if fadeType == FadeType.NONE:
    return

  fadeTime += delta
  var t:float = fadeTime / fadeDuration

  # Get destination alpha type.
  var destAlpha:float = 0.0
  var srcAlpha:float
  if fadeType == FadeType.FADE_IN:
    srcAlpha = 1.0
    destAlpha = 0.0
  elif fadeType == FadeType.FADE_OUT:
    srcAlpha = 0.0
    destAlpha = 1.0

  # End?
  if t >= 1.0:
    fadeUpdate.emit(1.0)
    var cFade = fadeType
    fadeType = FadeType.NONE
    $Overlay.color.a = destAlpha
    inFade = false

    if cFade == FadeType.FADE_OUT:
      fadeOutEnd.emit()
    elif cFade == FadeType.FADE_IN:
      fadeInEnd.emit()
    
    return

  # TODO: Use curves
  $Overlay.color.a = srcAlpha + (destAlpha - srcAlpha) * t
  fadeUpdate.emit(t)
  pass

func fade(
  fade:FadeType = FadeType.FADE_IN,
  duration:float = 0.4,
  color:Color = Color(0, 0, 0, 1),
):
  if inFade:
    push_error("Transition: Cannot start a new fade while another is in progress.")
    return

  $Overlay.visible = true
  $Overlay.color = color
  fadeDuration = duration
  fadeTime = 0
  fadeType = fade
  inFade = true

  if fade == FadeType.FADE_IN:
    fadeInStart.emit()
    $Overlay.color.a = 0
  elif fade == FadeType.FADE_OUT:
    fadeOutStart.emit()
    $Overlay.color.a = 1