class_name TutorialAnimation
extends AnimationPlayer

var waiting_for_action : bool = false
var instructions : Array[TutorialInstruction]
var current_instruction : TutorialInstruction

var current_keyboard_texture : CompressedTexture2D
var current_joycon_texture : CompressedTexture2D
var current_ps_texture : CompressedTexture2D

@onready var texture_rect: TextureRect = $CanvasLayer/VBoxContainer/HBoxContainer/TextureRect
@onready var label: Label = $CanvasLayer/VBoxContainer/HBoxContainer/Label

func _ready() -> void:
	play("RESET")
	SignalBus.changed_input_type.connect(replace_sprites_by_type)

func setup(i : Array[TutorialInstruction]):
	instructions = i.duplicate()
	_setup()

func _setup():
	current_instruction = instructions.pop_front()
	if current_instruction == null:
		return
	current_keyboard_texture = load(Utils.get_button_icon(current_instruction.keyboard_button))
	current_joycon_texture = load(Utils.get_button_icon(current_instruction.joycon_button))
	current_ps_texture = load(Utils.get_button_icon(current_instruction.ps_button))
	replace_sprites_by_type(Globals.current_input_type)
	label.text = current_instruction.description

func replace_sprites_by_type(input_type : Utils.INPUT_TYPE):
	match input_type:
		Utils.INPUT_TYPE.KEYBOARD:
			texture_rect.texture = current_keyboard_texture
		Utils.INPUT_TYPE.PLAYSTATION:
			texture_rect.texture = current_ps_texture
		_:
			texture_rect.texture = current_joycon_texture

func fade_in():
	if current_instruction == null:
		waiting_for_action = false
		return
	play("fade_in")
	waiting_for_action = true

func _process(_delta: float) -> void:
	if waiting_for_action:
		if Input.is_action_just_pressed(current_instruction.hide_on_action):
			waiting_for_action = false
			play("fade_out")
			await animation_finished
			setup_next()

func setup_next():
	_setup()
	fade_in()
