extends Control

const SCREEN_HEIGHT: int = 600
const SCREEN_WIDTH: int = 1024
const LINE_HEIGHT: int = 150
const LETTER_SPACING: int = 20

var label: Resource = preload("res://typed_letter.tscn")
var labels: Array = []
var current_x: float = 0
var current_y: float = 0

onready var labels_node: Control = $Labels

var is_ready: bool = false

func _ready() -> void:
	Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
	offset_line(1)
	is_ready = true

func _input(event: InputEvent) -> void:
	if event is InputEventKey:
		var key_event: InputEventKey = event
		if key_event.pressed and not key_event.echo:
			var letter: String = OS.get_scancode_string(event.scancode)
			if event.physical_scancode >= KEY_0 and event.physical_scancode <= KEY_9:
				spawn_text(OS.get_scancode_string(event.physical_scancode))
			elif letter.length() == 1:
				spawn_text(OS.get_scancode_string(event.scancode))
			else:
				match key_event.physical_scancode:
					KEY_ENTER:
						offset_line()
					KEY_ESCAPE:
						offset_line(6)
					KEY_BACKSPACE:
						delete_last_text()

func offset_line(amount: int = 1) -> void:
	current_x = 0
	current_y = current_y + LINE_HEIGHT * amount
	var target_pos := Vector2(0, SCREEN_HEIGHT - (LINE_HEIGHT + current_y))
	var tween := get_tree().create_tween()
	var tweener := tween.tween_property(labels_node, "rect_position", target_pos, 0.3)
	tweener.from_current().set_trans(Tween.TRANS_CUBIC)
	if is_ready:
		$AudioStreamPlayer.stop()
		$AudioStreamPlayer.play()

func spawn_text(text: String) -> void:
	var instance : TypedLetter = label.instance()
	labels.push_back(instance)
	labels_node.add_child(instance)
	instance.rect_position = Vector2(current_x, current_y)
	instance.add_label(text)
	current_x = current_x + instance.get_width() + LETTER_SPACING
	if current_x > SCREEN_WIDTH:
		offset_line()

func delete_last_text() -> void:
	if not labels.empty():
		var last: TypedLetter = labels.back()
		if current_y == last.rect_position.y:
			current_x = last.rect_position.x
			labels.pop_back()
			last.delete_label()
