extends Node2D

# word stuff
var word_set
var word_set_file_path
var word_set_file
var word_set_content
var word_set_array

# init random
var alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N",
"O","P","Q","R","S","T","U","V","W","X","Y","Z"]
var comets = []
var comet_speed = 150

# numbers
var delay = 2
var spawn_timer = 0

# objects
var comet_source = preload("res://scenes/objects/game/comet.tscn")

# Runs on start
func _ready() -> void:
	
	# Load Corresponding Text File
	word_set_file_path = "res://gameplay/word_sets/" + word_set + ".txt"
	word_set_file = FileAccess.open(word_set_file_path, FileAccess.READ)
	
	# Gets file contents as text
	word_set_content = word_set_file.get_as_text()
	
	# Splits text file contents by line and removes the first entry (its just the name)
	word_set_array = word_set_content.split("\n", true)
	word_set_array.remove_at(0)
	
	if word_set_array[len(word_set_array)-1] == "":
		word_set_array.remove_at(len(word_set_array)-1)
	
	#print(word_set_array)

# Runs every frame
func _process(delta: float) -> void:
	spawn_timer += delta
	
	if spawn_timer >= delay:
		spawn_timer = 0
		spawn_word()

func spawn_word():
	var new_word = word_set_array[randi_range(0,len(word_set_array)-1)]
	var viewport_size = get_viewport_rect().size
	var offset = 0
	
	for char in new_word:
		if char != " ":
			var new_commet = comet_source.instantiate()
			new_commet.position = Vector2(128+offset,-128)
			new_commet.get_node("Sprite").get_node("Label").text = char
			new_commet.speed = comet_speed
			add_child(new_commet)
			comets.append(new_commet)
		offset += 75

func _input(event):
	if event is InputEventKey and event.pressed:
		if event.as_text() in alphabet:
			print(event.as_text())
			
			if len(comets) > 0:
				var comet = comets[0]
				if event.as_text() == comet.get_node("Sprite").get_node("Label").text:
					comets.erase(comet)
					comet.get_node("Sprite").play("cometbreak")
					$CometBreakSound.play()
					await comet.get_node("Sprite").animation_finished
					comet.queue_free()
