extends CharacterBody3D

@onready var terrain := get_node("../VoxelTerrain") as VoxelTerrain

var selected := false
var path : Array[Vector3i]

func _on_input_event(camera: Node, event: InputEvent, event_position: Vector3, normal: Vector3, shape_idx: int) -> void:
	if event is InputEventMouseButton and event.is_pressed():
		var button_event = event as InputEventMouseButton
		if button_event.button_index == MOUSE_BUTTON_LEFT:
			$ProgrammingUI.visible = true
			selected = true
		elif button_event.button_index == MOUSE_BUTTON_RIGHT:
			$ProgrammingUI.visible = false
			selected = false

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

func move_to_mouse_click():
	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.get_voxel_tool().raycast(origin, dir, 100)
	var path_finder := VoxelAStarGrid3D.new()
	path_finder.set_terrain(terrain)
	path_finder.set_region(AABB(Vector3.ONE * -100, Vector3.ONE * 200))
	path = path_finder.find_path(Vector3i(global_position), res.previous_position)
	if not path.is_empty():
		path.append(res.previous_position)
	for step in path:
		print(step)

func _process(delta: float) -> void:
	if not path.is_empty():
		var next_position := Vector3(path[0]) + Vector3.ONE * 0.5;
		if path.size() == 1:
			if next_position.distance_to(global_position) < 0.1:
				rotation.x = 0
				rotation.y = round(rotation.y/(PI/2))*PI/2
				rotation.z = 0
				print("arrived")
		if next_position.distance_to(global_position) < 0.1:
			global_position = next_position
			path.remove_at(0)
		else:
			look_at(next_position)
		velocity = (next_position - global_position).normalized() * 5
		move_and_slide()
