class_name Sword
extends Node2D

@onready var area_2d: Area2D = $Origin/Offset/Area2D
@onready var animation_player = $AnimationPlayer

var _direction
var _damage
var already_hit : Array = []
var _speed

func start(direction : Vector2, damage : int = 1, speed : float = 5):
	_direction = direction.normalized()
	_damage = damage
	rotate(atan2(_direction.x, -_direction.y))
	_speed = speed
	animation_player.play("spin", -1, speed)

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(_delta: float) -> void:
	if Globals.paused:
		animation_player.pause()
		return
	elif !animation_player.is_playing():
		animation_player.speed_scale = _speed
		animation_player.play()

func _on_area_2d_body_entered(body: Node2D) -> void:
	if not already_hit.has(body):
		already_hit.append(body)
	else:
		return
	if body.is_in_group("Enemy"):
		body.take_damage(_damage)
		body.knockback(_direction)
	
	if body is Interactable:
		body.switch_state()

func _on_area_2d_area_entered(area: Area2D) -> void:
	if not already_hit.has(area):
		already_hit.append(area)
	else:
		return
	if area.name == "Hitbox":
		var par = area.get_parent()
		if par.is_in_group("Player"):
			par.take_damage(_damage)
			par.knockback(_direction)
		elif par.is_in_group("Boss"):
			par.take_damage(_damage)
