class_name GameAgent
extends CharacterBody2D

@export var attack_damage = 1

var current_direction : Vector2 = Vector2(0, 1)
var sword = preload("res://scenes/nodes/weapons/sword.tscn")
var weapon = null

var movement_velocity = Vector2(0,0)
var knockback_velocity = Vector2(0,0)

var push_force = 200.0  # was 800 before sprites rework

@onready var animation_player : AnimationPlayer = get_node("AnimationPlayer")

func _ready() -> void:
	motion_mode = CharacterBody2D.MOTION_MODE_FLOATING  # s.t. when pushing e.g. a box from the top, it works

func _physics_process(delta: float) -> void:
	if Globals.paused and not Globals.forcing_player_movement:
		if animation_player.is_playing():
			animation_player.stop()
		return
	velocity = movement_velocity + knockback_velocity
	knockback_velocity = knockback_velocity.move_toward(Vector2(0,0), 500 * delta)
	move_and_slide()
	_animate()
	
	# pushing objects (after move_and_slide())
	for i in get_slide_collision_count():
		var c = get_slide_collision(i)
		if c.get_collider().is_in_group("PushableObject"):  # was "if c.get_collider() is Rigidbody2D"
			c.get_collider().apply_central_impulse(-c.get_normal() * push_force)

func move_with_speed(direction : Vector2, speed : float):
	if direction != Vector2(0,0):
		current_direction = direction.normalized()
	movement_velocity = direction.normalized() * speed

func attack():
	if weapon: return
	weapon = sword.instantiate()
	add_child(weapon)
	weapon.start(current_direction, attack_damage)
	AudioManager.create_audio(SoundEffect.SOUND_EFFECT_TYPE.SWORD_SWING)
	
	await weapon.animation_player.animation_finished
	weapon.queue_free()
	weapon = null
	

func knockback(direction : Vector2, strength = 100):  # was 200 before the sprite reworks
	knockback_velocity = direction.normalized() * strength

func take_damage(_damage : int):
	pass

func _animate():
	if velocity:
		animation_player.play("walk")
	else:
		animation_player.stop()
