extends Control
class_name TextTyper

signal text_typing_started
signal text_typing_finished

@export var sound: AudioStream

@export_range(0, 0.25) var speed: float = 0.02
var currentAnimTime: float
var animating: bool

@export var imageField: Sprite2D
@export var characterPool: Array[Texture2D]

@onready var text = $RichTextLabel


func _ready():
	text.set_text("")
	_hide_box()


func animate_text_in(text: String):
	text_typing_started.emit()
	self.text.visible_characters = 0
	self.text.set_text(text)
	
	_show_box()
	
	currentAnimTime = 0
	animating = true
	
	imageField.texture = characterPool.pick_random()


func _process(delta):
	if (not animating):
		return
	
	currentAnimTime += delta
	if (currentAnimTime >= speed):
		_show_next_character()
		currentAnimTime = 0


func _show_next_character():
	text.visible_characters += 1
	_play_sound()
	if text.visible_characters == text.get_total_character_count():
		animating = false
		text_typing_finished.emit()


func _play_sound():
	SoundManager.play_sound_with_pitch(sound, randf_range(0.9, 1.1))


func _hide_box():
	visible = false
func _show_box():
	visible = true


func _on_event_complete():
	_hide_box()
func _on_event_fail():
	_hide_box()
