extends Node

@export var Mine: PackedScene
@export var max_range = 1500
@export var min_range = 15
@export var max_ammo = 5
@export var cast_time = 0.5
@export var cooldown_time = 1.0

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 not Input.is_action_just_pressed("play_card") or 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):
	$MineSFX.play()
	var mine = Mine.instantiate()
	mine.position = position
	if activator.get_collision_layer_value(1): # player object
		mine.get_node("Area2D").set_collision_layer_value(1, false)
		mine.get_node("Area2D").set_collision_layer_value(2, true)
		ammo -= 1
	elif activator.get_collision_layer_value(2): # enemy object
		mine.get_node("Area2D").set_collision_layer_value(1, true)
		mine.get_node("Area2D").set_collision_layer_value(2, false)
	else:
		assert(false, "who are you, activator?")
	world.add_child(mine)

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

func get_ammo():
	return ammo
