# Hurry Curry! - a game about cooking
# Copyright (C) 2025 Hurry Curry! contributors
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, version 3 of the License only.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
class_name SceneTransition
extends Control

@onready var black_anim: AnimationPlayer = $black_fader
@onready var text_anim: AnimationPlayer = $text_fader
@onready var text: Label = $text_margin/text

var s_current = false
var s_target = false
var fading = false

signal animation_end

func _ready():
	$black.visible = true
	text.visible = true
	text.text = ""
	Settings.hook_changed_init("ui.transition_speed", self, func(v):
		black_anim.speed_scale = v
		text_anim.speed_scale = v
	)

func set_loading_text(s: String):
	text.text = s
	text_anim.play("fade")

func next():
	while fading: await animation_end
	if s_target == s_current: return
	fading = true
	if s_target:
		if text.text != "":
			text_anim.play_backwards("fade")
			await text_anim.animation_finished
		black_anim.play_backwards("fade")
		await black_anim.animation_finished
		self.mouse_filter = Control.MOUSE_FILTER_IGNORE
		set_loading_text("")
		s_current = true
	else:
		self.mouse_filter = Control.MOUSE_FILTER_STOP
		black_anim.play("fade")
		await black_anim.animation_finished
		await get_tree().process_frame # animation finishes one frame early
		s_current = false
	fading = false
	animation_end.emit()
	await next()

func fade_in():
	s_target = true
	await next()
func fade_out():
	s_target = false
	await next()

func _exit_tree():
	if fading: push_error("SceneTransition destroyed while fading")
