extends PanelContainer

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

@onready var cpu := get_parent() as CPU

func memory_setup() -> void:
	var register_types : Dictionary[int, String]
	for module in cpu.modules:
		register_types.assign(module.get_register_types())
	
	for i in range(cpu.register_size):
		var entry := memory_entry.instantiate() as Control
		(entry.get_node("address") as Label).text = "[ /" + str(i).pad_zeros(2) + " ]"
		(entry.get_node("value") as SpinBox).value = 0
		(entry.get_node("type") as Label).text = register_types[i] if register_types.has(i) else "Free"
		memory.add_child(entry)

func _process(_delta: float) -> void:
	# Set execution indicator
	for line in code_editor.get_executing_lines():
		code_editor.set_line_as_executing(line, false)
	if cpu.cobor_vm.get_program_size() < cpu.cobor_vm.get_program_counter():
		code_editor.set_line_as_executing(cpu.cobor_vm.get_program_counter(), true)
	# Show register values
	var registers := cpu.cobor_vm.get_registers()
	for i in range(registers.size()):
		var entry := memory.get_child(i) as Control
		(entry.get_node("value") as SpinBox).value = registers[i]

func _on_compile_button_pressed() -> void:
	cpu.compile_code(code_editor.text)

func _on_stop_button_pressed() -> void:
	code_editor.editable = true
	cpu.stop()

func _on_play_button_pressed() -> void:
	if code_editor.editable:
		cpu.compile_code(code_editor.text)
	code_editor.editable = false
	cpu.run()

func _on_pause_button_pressed() -> void:
	cpu.pause()

func _on_step_button_pressed() -> void:
	if code_editor.editable:
		cpu.compile_code(code_editor.text)
	code_editor.editable = false
	cpu.run_step()
