extends Node

var global_variables = {}

@onready var text_box_scene = preload("res://prefabs/ink_template.tscn")

var text_box: Control

var is_dialog_active = false
var can_enter_dialogue = true

@export var start_time = 50
@export var decrease_speed = 0.5

signal dialogue_finished(time_to_add: int)

func start_dialog(lines: Resource):
	if lines == null:
		return
	if is_dialog_active or !can_enter_dialogue:
		return
	
	_show_text_box()
	text_box.variables = global_variables
	text_box._setup_story(lines)
	
	is_dialog_active = true
	can_enter_dialogue = false

func _show_text_box():
	text_box = text_box_scene.instantiate()
	get_tree().root.add_child(text_box)

const DIALOGUE_COOLDOWN = .5
var dialogue_cooldown = 0

func _process(delta):
	if (
		Input.is_action_just_pressed("advance_dialog") &&
		is_dialog_active
	):
		text_box._continue_story()
		if !text_box.active:
			_quit_dialogue()
	
	dialogue_cooldown -= delta
	if !is_dialog_active and dialogue_cooldown < 0:
		can_enter_dialogue = true

func _quit_dialogue():
	is_dialog_active = false
	global_variables = text_box.variables
	dialogue_finished.emit(global_variables["time_to_add"])
	global_variables["time_to_add"] = 0
	dialogue_cooldown = DIALOGUE_COOLDOWN
	text_box.queue_free()
