extends Node2D

@onready var sprite_2d: Sprite2D = $Sprite2D
@onready var shoot_point: Node2D = $shootPoint
@onready var projectiles: Node2D = $"/root/game/projectiles"
@onready var character: CharacterBody2D = $".."

var projectileScene = preload("res://scenes/projectile.tscn")

var is_aiming: bool = false

@export var cooldown: float = 0.5  # Cooldown duration in seconds
var cooldown_timer: float = 0.0  # Tracks time remaining for cooldown


func _ready():
	var joystick_count = Input.get_connected_joypads()
	for joystick in joystick_count:
		print("Joystick connected: ", Input.get_joy_name(joystick))

func _process(delta):
	# Update cooldown timer
	if cooldown_timer > 0:
		cooldown_timer -= delta

	var joystick_id = character.name.substr(1).to_int() - 1  # Assuming the first controller (ID 0)
	var right_stick_x = Input.get_joy_axis(joystick_id, JOY_AXIS_RIGHT_X)
	var right_stick_y = Input.get_joy_axis(joystick_id, JOY_AXIS_RIGHT_Y)
	
	var aim_direction = Vector2(right_stick_x, right_stick_y)
	# Check if the joystick is outside the dead zone
	if aim_direction.length() > 0.7:
		shoot_point.get_child(0).visible = true
		is_aiming = true
		aim_direction = aim_direction.normalized()
		rotation = aim_direction.angle()
		if aim_direction.x < 0:
			sprite_2d.flip_v = true
		else:
			sprite_2d.flip_v = false
	else:
		#rotation = 0
		shoot_point.get_child(0).visible = false
		is_aiming = false
		sprite_2d.flip_v = false
		
		# Handle shooting with cooldown
	if Input.is_action_just_pressed("shoot_" + character.name) and is_aiming and cooldown_timer <= 0:
		shoot()
		cooldown_timer = cooldown  # Reset cooldown timer


func shoot():
	var projectile = projectileScene.instantiate()
	projectile.rotation = rotation
	projectile.position = shoot_point.global_position
	projectile.shot_by = character
	projectiles.add_child(projectile)
