extends CanvasLayer

const _ANIM_LOADING: StringName = &"hover"

var fade_in_duration: float = 2.0
var fade_out_duration: float = 2.0
var is_fading: bool = false
var is_loading: bool = false


@onready var interactive_loader: InteractiveLoader = %InteractiveLoader
@onready var color_rect: ColorRect = %ColorRect
@onready var loading_hint_animations: AnimationPlayer = %LoadingHintAnimations
@onready var loading_hint: TextureRect = %LoadingHint
@onready var loading_label: RichTextLabel = $LoadingLabel


func _ready() -> void:
	loading_label.hide()
	color_rect.hide()
	color_rect.color.a = 0.0


func load_to_path(path: String, initial_level: String = "") -> void:
	if is_loading:
		return

	is_loading = true

	await fade_in()
	#await get_tree().create_timer(1.0).timeout

	# Load the initial level into memory first, so it can be retrived by other things later.
	if not initial_level.is_empty():
		LevelLoader.initial_level_reference = await interactive_loader.load_threaded(initial_level)

	print("Initial Level Reference Loaded: ", LevelLoader.initial_level_reference)

	var scene: PackedScene = await interactive_loader.load_threaded(path)

	print("Scene Loaded: ", scene)
	assert(is_instance_valid(scene), "Scene is invalid.")

	get_tree().change_scene_to_packed(scene)
	get_tree().paused = false

	fade_out()
	is_loading = false


func fade_in() -> void:
	color_rect.show()
	is_fading = true

	var tween: Tween = create_tween()
	tween.tween_property(color_rect, ^"color:a", 1.0, fade_in_duration)
	await tween.finished

	is_fading = false

	set_loading_hints_visible(true)


func fade_out() -> void:
	set_loading_hints_visible(false)

	is_fading = true

	var tween: Tween = create_tween()
	tween.tween_property(color_rect, ^"color:a", 0.0, fade_out_duration)
	await tween.finished

	color_rect.hide()
	is_fading = false


func set_loading_hints_visible(value: bool) -> void:
	loading_hint.visible = value
	loading_label.visible = value

	if value:
		loading_label.set_text(loading_label.text) # Restart the effect.
		loading_hint_animations.play(_ANIM_LOADING)
	else:
		loading_hint_animations.stop()
