extends Node

@onready var code_editor := $%Code as CodeEdit
@onready var memory := $%Memory as VBoxContainer
@onready var memory_entry := load("uid://dqwi5rekytyds") as PackedScene
var cobor_vm  := CoborVirtualMachine.new() 

func _ready() -> void:
	cobor_vm.set_registers(8,[])
	for i in range(8):
		var entry := memory_entry.instantiate() as Control
		(entry.get_node("address") as Label).text = "/" + str(i) + " = "
		(entry.get_node("value") as SpinBox).value = 0
		memory.add_child(entry)

func _tick() -> void:
	if code_editor.editable: return
	for line in code_editor.get_executing_lines():
		code_editor.set_line_as_executing(line, false)
	code_editor.set_line_as_executing(cobor_vm.get_program_counter(), true)
	var err := cobor_vm.run_step()
	if not err.is_empty():
		print(err);
	var registers := cobor_vm.get_registers()
	for i in range(8):
		var entry := memory.get_child(i) as Control
		(entry.get_node("value") as SpinBox).value = registers[i]

func _on_compile_button_pressed() -> void:
	var text := code_editor.text
	var errors := cobor_vm.parse_source_code(text)
	if errors.is_empty():
		print("Compiling Ok!")
	else:
		for error in errors:
			print(error)

func _on_stop_button_pressed() -> void:
	code_editor.editable = true
	$Timer.stop()
	cobor_vm.set_registers(8,[])

func _on_play_button_pressed() -> void:
	code_editor.editable = false
	_on_compile_button_pressed();
	$Timer.start()

func _on_pause_button_pressed() -> void:
	$Timer.stop()


func _on_step_button_pressed() -> void:
	code_editor.editable = false
	_tick()
