extends Module

var enabled := true

var pos_x_register_index:int
var pos_y_register_index:int
var pos_z_register_index:int

var pos := Vector3i.ZERO

func _ready() -> void:
	if Terrain.instance == null:
		print("No terrain to get clicks from")

func get_register_reservation_size()->int:
	return 3

func set_reserved_registers(index:int)->void:
	pos_x_register_index = index
	pos_y_register_index = index+1
	pos_z_register_index = index+2

func get_register_types()->Dictionary[int, String]:
	return { 
		pos_x_register_index: "[X] Click", 
		pos_y_register_index: "[Y] Click",
		pos_z_register_index: "[Z] Click" 
		}

func _unhandled_input(event: InputEvent) -> void:
	if not enabled: return
	if event is InputEventMouseButton and event.is_pressed():
		var button_event = event as InputEventMouseButton
		if button_event.button_index == MOUSE_BUTTON_LEFT:
			set_click_registers()
		elif button_event.button_index == MOUSE_BUTTON_RIGHT:
			pass

func set_click_registers()->void:
	var mouse_pos_2d := get_viewport().get_mouse_position()
	var current_camera := get_viewport().get_camera_3d()
	var origin := current_camera.project_ray_origin(mouse_pos_2d)
	var dir := current_camera.project_ray_normal(mouse_pos_2d)
	var res := Terrain.instance.get_voxel_tool().raycast(origin, dir, 100)
	pos = res.previous_position

func early_tick()->void:
	var registers := cpu.cobor_vm.get_registers()
	registers[pos_x_register_index] = pos.x
	registers[pos_y_register_index] = pos.y
	registers[pos_z_register_index] = pos.z
	cpu.cobor_vm.set_registers(cpu.register_size, registers)
