extends Node3D

@onready var tower_blueprint = preload("res://Towers/tower.tscn")
@onready var selected_tower_button : TowerButton = $CanvasLayer/UI/ShopPanel/VBoxContainer/PierreButton

@onready var cam : Camera3D = $Camera3D
@onready var selector : Node3D = $Selector
@onready var the_cube : TheCube = %TheCube


var team_in_action : Array[Tower]
var team_in_rest : Array[Tower]
var target_tower : Tower 
var in_build_menu : bool = false

var selected_collider : CollisionObject3D

func _ready() -> void:
	$Spawner.spawn_next_wave()
	$CanvasLayer/UI/ShopPanel.visible = in_build_menu
	EventBus.tower_selected.connect(_on_EventBus_tower_selected)


func _process(delta: float) -> void:
	handle_player_controls()
	if Input.is_action_just_pressed("build"):
		if not selected_collider:
			return
		
		if selected_collider.collision_layer == 1:
			build_tower(tower_blueprint)
		if selected_collider is TheCube:
			open_shop()
		else:
			close_shop()
	
	if Input.is_action_just_pressed("rest"):
		close_shop()
		if target_tower:
			send_to_rest(target_tower)


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
		selected_collider = null
		return
	
	var collider : CollisionObject3D = ray_result.get("collider")
	selected_collider = collider
	
	selector.visible = true
	selector.global_position = collider.global_position
	selector.global_position += Vector3(0.0,0.2,0.0)
	
	if selected_collider is Tower:
		target_tower = collider
	else:
		target_tower = null

# Refactoriser ce code
func build_tower(scene : PackedScene) -> void:
	if !selector.visible:
		return
	
	var temp_tower : Tower = scene.instantiate()
	
	
	#Move existing tower
	for tower : Tower in team_in_action:
		if tower.tower_name == temp_tower.tower_name:
			move_tower(tower)
			return
	
	#Send to action a resting tower
	for tower : Tower in team_in_rest:
		if tower.tower_name == temp_tower.tower_name:
			move_tower(tower)
			send_to_action(tower)
			return
	
	#Build Tower
	if temp_tower.price < the_cube.money:
		#Can't build
		print("Too costly")
		return
	else : 
		#Can build
		the_cube.money -= temp_tower.price
		temp_tower.tower_button = selected_tower_button
		add_child(temp_tower)
		selected_tower_button.tower_in_game = temp_tower
	
	send_to_action(temp_tower)
	move_tower(temp_tower)



func move_tower(tower : Tower):
	tower.global_position = selector.global_position


func send_to_rest(tower : Tower):
	team_in_action.erase(tower)
	team_in_rest.append(tower)
	tower.is_rest = true


func send_to_action(tower : Tower):
	team_in_rest.erase(tower)
	team_in_action.append(tower)
	tower.is_rest = false

func open_shop():
	if in_build_menu:
		close_shop()
		return
	
	in_build_menu = true
	$CanvasLayer/UI/ShopPanel.visible = in_build_menu



func close_shop():
	in_build_menu = false
	$CanvasLayer/UI/ShopPanel.visible = in_build_menu


func _on_EventBus_tower_selected(tower : PackedScene, tower_button : TowerButton):
	tower_blueprint = tower
	selected_tower_button = tower_button


func _on_cube_icon_pressed() -> void:
	open_shop()
