extends Node

@export var KatanaSlash: PackedScene
@export var max_range = 50
@export var min_range = 50
@export var max_ammo = 20
@export var cast_time = 0.2
@export var cooldown_time = 0.5

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):
	$KatanaSFX.play()
	var katana = KatanaSlash.instantiate()
	var target = activator.get_target_pos()
	activator.add_child(katana) # KatanaSlash might have to be detached later?
	katana.position = position
	katana.look_at(target)
	if activator.get_collision_layer_value(1): # player object
		katana.get_node("Area2D").set_collision_layer_value(1, false)
		katana.get_node("Area2D").set_collision_layer_value(2, true)
		ammo -= 1
	elif activator.get_collision_layer_value(2): # enemy object
		katana.get_node("Area2D").set_collision_layer_value(1, true)
		katana.get_node("Area2D").set_collision_layer_value(2, false)
	else:
		assert(false, "who are you, activator?")
	# world.add_child(katana)
	
func discard(world, activator, do_ability):
	ammo = max_ammo

func get_ammo():
	return ammo
