extends Node3D

@onready var tower_blueprint = preload("res://Towers/tower.tscn")

@onready var cam : Camera3D = $Camera3D
@onready var selector : Node3D = $Selector


#func _ready() -> void:
	#$Spawner.spawn_next_wave()

func _process(delta: float) -> void:
	handle_player_controls()
	if Input.is_action_just_pressed("build"):
		build_tower(tower_blueprint)


func handle_player_controls() -> void:
	var space_state : PhysicsDirectSpaceState3D = get_world_3d().direct_space_state
	var mouse_pos : Vector2 = get_viewport().get_mouse_position()
	
	var origin : Vector3 = cam.project_ray_origin(mouse_pos)
	var end : Vector3 = origin + cam.project_ray_normal(mouse_pos) * 100
	var ray : PhysicsRayQueryParameters3D = PhysicsRayQueryParameters3D.create(origin, end)
	ray.collide_with_bodies = true
	
	var ray_result : Dictionary = space_state.intersect_ray(ray)
	
	if ray_result.is_empty():
		selector.visible = false
		return
	
	selector.visible = true
	var collider : CollisionObject3D = ray_result.get("collider")
	selector.global_position = collider.global_position
	selector.global_position += Vector3(0.0,0.2,0.0)


func build_tower(scene : PackedScene) -> void:
	if !selector.visible:
		return
	
	var temp_cannon : Tower = scene.instantiate()
	add_child(temp_cannon)
	temp_cannon.global_position = selector.global_position
