extends Node

@export var CursorBullet: PackedScene = preload("res://CardInjects/CursorGun/cursor_bullet.tscn")
@export var max_range = 50
@export var min_range = 50
@export var max_ammo = 30
@export var cast_time = 0.05
@export var cooldown_time = 0.1

var ammo = max_ammo
var cast_timer: Timer = Timer.new()
var cooldown_timer: Timer = Timer.new()

func _ready():
	add_child(cast_timer)
	cast_timer.wait_time = cast_time
	cast_timer.one_shot = true
	add_child(cooldown_timer)
	cooldown_timer.wait_time = cooldown_time
	cooldown_timer.one_shot = true

func activate(world, activator):
	if cooldown_timer.time_left:
		return
	
	var target = activator.get_target_pos()
	var position = activator.position
	position = position.direction_to(target) \
		* clamp(position.distance_to(target), min_range, max_range)
	
	cast_timer.timeout.connect(_activate.bind(world, activator, position), CONNECT_ONE_SHOT)
	cast_timer.start()
	cooldown_timer.start()

func _activate(_world, activator, position):
	$ShootSFX.play()
	var bullet = CursorBullet.instantiate()
	bullet.collision_mask = ~activator.collision_mask
	activator.add_child(bullet)
	bullet.position = position
	bullet.look_at(activator.get_target_pos())
	if activator.get_collision_layer_value(1): # player object
		bullet.set_collision_layer_value (1, false)
		bullet.set_collision_layer_value(2, true)
		ammo -= 1
	elif activator.get_collision_layer_value(2): # enemy object
		bullet.set_collision_layer_value(1, true)
		bullet.set_collision_layer_value(2, false)
	else:
		assert(false, "who are you, activator?")

func discard(world, activator, do_ability):
	ammo = max_ammo

func get_ammo():
	return ammo
