class_name PlayerBase
extends GameAgent

@export var move_speed = 100
@onready var collider: CollisionShape2D = $CollisionShape2D
@onready var center: Node2D = $MassCenter;
@export var iframe_duration : float = 1

@onready var sprite_2d: AnimatedSprite2D = $Sprite2D

var _iframe_countdown : float = 0

# added reference to timeshift so that external scripts can "force" a timeshift (e.g. the input recording)
@onready var time_shift : TimeShift = $"../TimeShift"

@onready var hitbox: Area2D = $Hitbox

var map_loader : MapLoader
var cached_direction : Vector2 = Vector2.ZERO;

func _ready() -> void:
	super._ready()

func move(direction : Vector2):
	cached_direction = direction;
	move_with_speed(direction, move_speed)

func animation_walk(direction : Vector2):
	cached_direction = direction
	move_with_speed(direction, (move_speed * 2.0)/3.0)

func take_damage(damage : int):
	if get_parent():
		get_parent().take_damage(damage)
	start_iframes()
	AudioManager.create_audio(SoundEffect.SOUND_EFFECT_TYPE.GET_HIT)

func set_timechecker():
	time_shift._set_timecheck_position()

func set_map_loader(ml : MapLoader):
	map_loader = ml
	time_shift.map_loader = ml
	set_timechecker()

func attack():
	if weapon: return
	weapon = sword.instantiate()
	center.add_child(weapon);
	weapon.get_node("Origin/Offset").position = Vector2(0, -50); # was Vector2(0, -50); before the sprite reworks
	weapon.area_2d.set_collision_mask_value(10, false)
	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 _animate():
	pass;

func start_iframes():
	_iframe_countdown = iframe_duration
	hitbox.process_mode = Node.PROCESS_MODE_DISABLED
	sprite_2d.modulate = Color(0.5, 0.5, 0.5)

func stop_iframes():
	hitbox.process_mode = Node.PROCESS_MODE_INHERIT
	sprite_2d.modulate = Color(1, 1, 1)

func _process(delta: float) -> void:
	if _iframe_countdown > 0:
		_iframe_countdown -= delta
		if _iframe_countdown <= 0:
			stop_iframes()
