class_name Dialog
extends Control

@export var char_delay := 0.02

var message_queue : Array[String] = []
var is_printing := false
var skip_requested := false
@export var dialogue_label : RichTextLabel

func _ready() -> void:
	dialogue_label.bbcode_enabled = true
	dialogue_label.visible_characters = 0

	EventBus.dialogue_requested.connect(add_to_queue)


func add_to_queue(msg: String) -> void:
	message_queue.append(msg)
	if not is_printing:
		visible = true
		is_printing = true
		get_tree().paused = true
		_show_messages()

func _show_messages() -> void:
	while not message_queue.is_empty():
		var next_msg : String = message_queue.pop_front()
		await _type_text(next_msg)
	
	_finish_dialogue()


func _type_text(msg: String) -> void:
	
	dialogue_label.text = msg
	dialogue_label.visible_characters = 0
	skip_requested = false

	for i in msg.length():
		if skip_requested:
			break
		
		dialogue_label.visible_characters = i + 1
		await get_tree().create_timer(char_delay, true, false, true).timeout

	dialogue_label.visible_characters = -1
	await _wait_for_input()

func _wait_for_input() -> void:
	skip_requested = false
	while not skip_requested:
		await get_tree().process_frame

func _finish_dialogue() -> void:
	dialogue_label.visible_characters = 0
	dialogue_label.text = ""
	visible = false
	is_printing = false
	get_tree().paused = false
	EventBus.dialogue_finished.emit()

func _input(event: InputEvent) -> void:
	if event.is_action_pressed("ui_accept") or (event is InputEventMouseButton and event.pressed):
		skip_requested = true
