extends Node

@onready var voxelTool := (get_parent() as VoxelTerrain).get_voxel_tool()

var block_edit := false

func _unhandled_input(event):
	if event is InputEventMouseButton and event.is_pressed():
		if block_edit:
			if event.button_index == MOUSE_BUTTON_LEFT:
				perform_block_action(true)
			elif event.button_index == MOUSE_BUTTON_RIGHT:
				get_tree().create_timer(0.15).timeout.connect(
					func():
						if not Input.is_mouse_button_pressed(MOUSE_BUTTON_RIGHT):
							perform_block_action(false)
				)

func perform_block_action(add_block:bool)->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 := voxelTool.raycast(origin, dir, 50)
	if res != null:
		if add_block: 
			voxelTool.set_voxel(res.previous_position, 1)
		else:
			voxelTool.set_voxel(res.position, 0)

func _on_button_toggled(toggled_on: bool) -> void:
	block_edit = toggled_on
