extends Node3D
class_name BuildingManager

@export_flags_3d_physics var buildings_layer_mask: int = 0b10
var placing_building: Building = null

func start_placement(scene: PackedScene) -> void:
	var object: Node = scene.instantiate()
	add_child(object)
	if object is Building:
		placing_building = object
		placing_building._start_placement()
		
func _input(event: InputEvent) -> void:
	if placing_building == null:
		return
	if event is InputEventMouseButton:
		if event.is_action("building_place"):
			placement_mouse_input((event as InputEventMouseButton).global_position, true)
			get_viewport().set_input_as_handled()
		elif event.is_action("building_cancel"):
			placement_cancel()
			get_viewport().set_input_as_handled()
	elif event is InputEventMouseMotion:
		placement_mouse_input((event as InputEventMouseMotion).global_position, false)
		get_viewport().set_input_as_handled()
			
func placement_mouse_input(screen_position: Vector2, confirmed: bool) -> void:
	# try to raycast to see what we clicked on/are hovering
	var camera: Camera3D = get_viewport().get_camera_3d()
	var ray_origin: Vector3 = camera.project_ray_origin(screen_position)
	var ray_normal: Vector3 = ray_origin + camera.project_ray_normal(screen_position) * 200
	var params: PhysicsRayQueryParameters3D = PhysicsRayQueryParameters3D.create(ray_origin, ray_normal)
	params.collision_mask = (1 << 31) | (1 << 1) | (1) # selectables, buildings, terrain
	if placing_building.collision_shape != null:
		params.exclude = [placing_building.get_rid()]
	var result: Dictionary = get_world_3d().direct_space_state.intersect_ray(params)
	
	var placment_feedback: int = 0
	if result.has("collider") and result["collider"] is Building:
		placment_feedback = placing_building._placement_select_building(result["collider"] as Building, confirmed)
	elif result.has("position"):
		DebugDraw3D.draw_sphere(result["position"] as Vector3)
		placment_feedback = placing_building._placement_select_position(result["position"] as Vector3, confirmed)

	if placment_feedback & Building.PLACEMENT_COMPLETED:
		placing_building._end_placement()
		placing_building = null

func placement_cancel() -> void:
	placing_building.queue_free()
	placing_building = null