class_name WeaponController extends Node3D
@export_category("WeaponController")

# ---------------------------------------------------------------------
# Main weapon params
# ---------------------------------------------------------------------
@export var damage: int = 0
# cooldown interval in seconds
@export var cooldown: float = 0
@export var mag_capacity: int = 0
# bullet speed in m/s
@export var bullet_speed: int = 200
@export var bullet_spread_script: GDScript
 
var map_controller: MapController
@onready var cooldown_timer: Timer = $CooldownTimer

var can_shoot: bool = true
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	cooldown_timer.wait_time = cooldown
	
	
@onready var bullet_trace_distance: Node3D = $BulletTraceDistance
@onready var bullet_trail_end: Node3D = $BulletTrailEnd
@onready var gun_animation = $ShotAnimation
func shoot() -> Error:
	if can_shoot:
		can_shoot = false
		var bullet_start_node: Node3D = bullet_trace_distance.find_child("Start")
		var bullet_end_node: Node3D = bullet_trace_distance.find_child("End")
		gun_animation.play("shot")
		cooldown_timer.start()
		
		if bullet_start_node and bullet_end_node:
			var path := "res://scenes/weapon/misc/bullet_trail_generic.tscn"
			if not ResourceLoader.exists(path):
				return ERR_DOES_NOT_EXIST
			var scene: PackedScene = ResourceLoader.load(path)
			if not scene.can_instantiate():
				return ERR_CANT_OPEN
			
			var node: MeshInstance3D = scene.instantiate()
			node.init(bullet_start_node.position, bullet_end_node.position)
			#var root := get_tree().get_root()
			bullet_start_node.add_child(node)
			return OK
		else:
			push_warning("Couldn't generate a bullet trace, no distance node found")
			return ERR_BUG
	return OK

	# -- TODO: It should not be hardcoded

func set_map_controller(map_node: MapController):
	map_controller = map_node

func attack(bullet_starting_point: Node3D):
	if can_shoot:
		can_shoot = false
		map_controller.spawn_bullet(bullet_starting_point, bullet_speed, damage)
		cooldown_timer.start()

func make_invisible() -> void:
	for child in find_children("*"):
		if child is MeshInstance3D:
			child.set_layer_mask_value(1, false)
			child.set_layer_mask_value(20, false)
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	pass


func _on_cooldown_timer_timeout() -> void:
	can_shoot = true
