class_name AnchoredRemnant
extends Node2D

@onready var player_base: PlayerBase = $PlayerBase  # own child
var player: Player  # the original player. e.g. for if you take dmg

var own_health = PlayerVariables.remnant_max_health

var moving_up = false
var moving_down = false
var moving_left = false
var moving_right = false

var bodies : Array[PlayerBase]

# get inputs from input recording script.
# move along

func _physics_process(_delta: float) -> void:
	if Globals.paused:
		return
	# movement
	var move_vector = Vector2.ZERO
	if moving_up:
		move_vector += Vector2.UP
	if moving_down:
		move_vector += Vector2.DOWN
	if moving_left:
		move_vector += Vector2.LEFT
	if moving_right:
		move_vector += Vector2.RIGHT
	player_base.move(move_vector)

func translate_replay_inputs(input):
	# move
	if input == Utils.RECORDED_ACTIONS.UP:
		moving_up = true
	if input == Utils.RECORDED_ACTIONS.DOWN:
		moving_down = true
	if input == Utils.RECORDED_ACTIONS.LEFT:
		moving_left = true
	if input == Utils.RECORDED_ACTIONS.RIGHT:
		moving_right = true
	
	# release move
	if input == Utils.RECORDED_ACTIONS.RELEASE_UP:
		moving_up = false
	if input == Utils.RECORDED_ACTIONS.RELEASE_DOWN:
		moving_down = false
	if input == Utils.RECORDED_ACTIONS.RELEASE_LEFT:
		moving_left = false
	if input == Utils.RECORDED_ACTIONS.RELEASE_RIGHT:
		moving_right = false
			
	# attack
	if input == Utils.RECORDED_ACTIONS.ATTACK:
		player_base.attack()
	if input == Utils.RECORDED_ACTIONS.TIME_SHIFT_TO_PRESENT:
		player_base.time_shift.trigger(Utils.TIME.PRESENT)
	if input == Utils.RECORDED_ACTIONS.TIME_SHIFT_TO_PAST:
		player_base.time_shift.trigger(Utils.TIME.PAST)

func die():
	queue_free()

func take_damage(damage : int):
	# the player takes damage from the remnant being attacked
	player.take_damage(damage)
	# remnant can only take a maximum amount of hits
	own_health -= damage
	if own_health <= 0:
		die()

func _on_area_2d_body_shape_entered(_body_rid: RID, body: Node2D, _body_shape_index: int, _local_shape_index: int) -> void:
	if body is PlayerBase and not body == player_base and not bodies.has(body):
		bodies.append(body)

func _on_area_2d_body_shape_exited(_body_rid: RID, body: Node2D, _body_shape_index: int, _local_shape_index: int) -> void:
	if body is PlayerBase and bodies.has(body):
		bodies.erase(body)
	if bodies.is_empty():
		player_base.set_collision_layer_value(1, true)
		player_base.set_collision_mask_value(9, true)
