extends Control

@onready var shake_tween: Node = $Control/Wizard/ShakeTween
@onready var animation_player: AnimationPlayer = $AnimationPlayer

@onready var node_2d: Node2D = $Control/Wizard/Node2D
var rotatable : Array[Node2D]
var rotating_counter = 0
@export var rotation_speed = 4
var finished_animation = false

@onready var dialogue_box: Control = $DialogueBox

func _ready() -> void:
	if is_inside_tree():
		await get_tree().create_timer(1).timeout 
	if Globals.screen_flash_effects:
		animation_player.play("intro_cutscene_start")
	else:
		animation_player.play("intro_cutscene_start_no_screen_flash")
		await animation_player.animation_finished
		if is_inside_tree():
			await get_tree().create_timer(1).timeout 
		animation_player.play("intro_cutscene_middle_no_screen_flash")

func _process(delta: float) -> void:
	if not rotatable or rotatable.is_empty():
		return
	for i in range(rotating_counter):
		rotatable[i].rotation += rotation_speed * delta
	if rad_to_deg(rotatable[rotating_counter-1].rotation) >= 45:
		_add_new_fireball()
	if not finished_animation and rotating_counter>= rotatable.size():
		finished_animation = true
		animation_player.play("intro_cutscene_end")
		await animation_player.animation_finished
		start_dialogue()

func shake_wizard_increase():
	shake_tween.start_increase()
	await shake_tween.tween_completed
	animation_player.play("intro_cutscene_middle")

func shake_wizard_decrease():
	shake_tween.start_decrease(1)

func _add_new_fireball():
	var cur = rotating_counter
	rotating_counter = min(rotating_counter + 1, rotatable.size()) 
	if cur != rotating_counter:
		AudioManager.create_audio(SoundEffect.SOUND_EFFECT_TYPE.FIREBALL)

func rotate():
	for node in node_2d.get_children():
		if node is Node2D:
			rotatable.append(node)
	rotating_counter = 1

func start_dialogue():
	dialogue_box.start()

func _on_dialogue_box_dialogue_finished() -> void:
	SceneChanger.change_scene_to(Utils.GAME_SCENES.GAME)

func play_flash_audio():
	AudioManager.create_audio(SoundEffect.SOUND_EFFECT_TYPE.THUNDER)
