class_name cCommandLine
extends CanvasLayer

var commands_directory = DirAccess.open("res://Scripts/Gameplay/CommandLine/Commands/")

@export var output_text: TextEdit
@export var input_line: LineEdit
var commands: Dictionary = {}
	
func _ready():
	load_commands()
	input_line.text_submitted.connect(self._on_command_entered)

# To make a new command, write it in ./Commands with a main() function for entry.
# This function will automatically find and register all command files
func load_commands():
	if not commands_directory:
		push_error("Failed to open commands folder!")
		return
		
	commands_directory.list_dir_begin()
	var file_name = commands_directory.get_next()
	
	while file_name != "":
		if file_name.ends_with(".gd"):
			var command_name = file_name.get_basename().to_lower()
			var script = load("res://Scripts/Gameplay/CommandLine/Commands/" + file_name)
			commands[command_name] = script
		file_name = commands_directory.get_next()
	commands_directory.list_dir_end()

func _print(text: String) -> void:
	var line = output_text.get_line_count() - 1
	output_text.insert_text(text + "\n", line, 0)

func _on_command_entered(new_text: String) -> void:
	input_line.clear()
	_print("> " + new_text)
	
	# Store command and ensure its not empty
	var parts = new_text.strip_edges().split(" ")
	if parts.size() == 0:
		return
	
	# Parse command and arguments
	var cmd = parts[0].to_lower()
	var args = parts.slice(1, parts.size())
	
	if commands.has(cmd):
		var cmd_script = commands[cmd].new()  # Instantiate the script
		if cmd_script.has_method("main"):
			# Run script
			cmd_script.main(args, self)
		else:
			_print("DEV ERROR !\nCommand '%s' has no main() function!" % cmd)
	else:
		_print("Unknown command: %s" % cmd)
		input_line.text = ""  # Clear input
