extends TextEdit

signal enter_key_pressed
signal close_pressed

@export
var LIMIT: int = 10
var current_text = ''
var cursor_line = 0
var cursor_column = 0

func _ready():
	text_changed.connect(_on_text_changed)

func _input(event):
	if event is InputEventKey and event.pressed:
		if event.alt_pressed && event.keycode == KEY_A:
			close_pressed.emit()
		if has_focus():
			if event.keycode == KEY_ENTER || event.keycode == KEY_KP_ENTER:
				enter_key_pressed.emit()

func _on_text_changed():
	if text.contains("\n"):
		text = text.replace("\n", "")
	
	var new_text : String = text
	if new_text.length() > LIMIT:
		text = current_text
		# when replacing the text, the cursor will get moved to the beginning of the
		# text, so move it back to where it was 
		set_caret_line(cursor_line)
		set_caret_column(cursor_column)

	current_text = text
	# save current position of cursor for when we have reached the limit
	cursor_line = get_caret_line()
	cursor_column = get_caret_column()
