extends Node
class_name CutsceneManager

signal loaded(cutscene_name: String)
signal started(cutscene_name: String)
signal issued_command(command: CutsceneCommand, manager: CutsceneManager)
signal finished(cutscene_name: String)

@export var cutscene: Cutscene

var is_running = false
@onready var _step = -1
var _current_command: CutsceneCommand: get = get_current_command
var _inner_timer = 0.0

var root: Node = self

func _process(delta):
	if _inner_timer > 0.0:
		_inner_timer -= delta
		if _inner_timer <= 0.0:
			step()

func get_current_command() -> CutsceneCommand:
	return _current_command
	
func step() -> void:
	_step += 1
	if(_step == 0):
		is_running = true
		started.emit(cutscene.resource_name)
	if(_step >= cutscene.commands.size()):
		is_running = false
		finished.emit(cutscene.resource_name)
	else:
		_current_command = cutscene.commands[_step]
		issued_command.emit(_current_command, self)

func load_cutscene(new_cutscene: Cutscene, root_node: Node = null) -> void:
	cutscene = new_cutscene
	_step = -1
	is_running = false
	root = root_node if root_node != null else self
	loaded.emit(cutscene.resource_name, cutscene.auto_start_on_load)

func _on_ui_dialogue_completed():
	step()

func _on_issued_command(command, _manager):
	if command is WaitCommand:
		_inner_timer = command.time
