class_name Player
extends Node2D

@export var map_loader : MapLoader

@onready var player_base : PlayerBase = $PlayerBase

var boss_anchor_state : Dictionary = {}

func _ready() -> void:
	if not map_loader:
		push_warning("No MapLoader assigned!")
	player_base.set_map_loader(map_loader)
	map_loader.handled_player_positioning.connect(player_base.time_shift.reset_set)
	SignalBus.boss_set_anchor.connect(save_state)
	SignalBus.boss_reload_anchor.connect(reload_state)

func _physics_process(_delta: float) -> void:
	if Globals.forcing_player_movement:
		return
	if Globals.paused or SceneChanger.mid_animation:
		player_base.move(Vector2.ZERO)
		return
	if Input.is_action_just_pressed("attack"):
		player_base.attack()
	player_base.move(Vector2(Input.get_axis("move_left", "move_right"), Input.get_axis("move_up", "move_down")).normalized())
	# no clip for testing purposes
	if Input.is_action_just_pressed("no_clip"):
		var col = player_base.get_node("CollisionShape2D")
		col.disabled = not col.disabled
		if col.disabled:
			player_base.move_speed *= 3
		else:
			player_base.move_speed /= 3
		

func take_damage(damage : int):
	PlayerVariables.change_health_delta(-damage)

func save_state():
	boss_anchor_state = {
		"global_position" = player_base.global_position,
	}

func reload_state():
	PlayerVariables.reset_health()
	if Globals.current_time == Utils.TIME.PAST:
		player_base.time_shift.trigger()
		await SignalBus.changed_player_position
	player_base.global_position = boss_anchor_state.get("global_position", player_base.global_position)
