class_name PlayerController extends Node2D

@export var auto_controlled_avatar: Player

##当前控制的Avatar
var _controlled_avatar: Player

## 当前输入状态
var move_input: Vector2 = Vector2.ZERO

func _enter_tree() -> void:
	GlobalEvent.register_player_controller(self)

func _ready() -> void:
	if auto_controlled_avatar:
		bind_avatar(auto_controlled_avatar)

##绑定avatar
func bind_avatar(p_avatar: Player) -> void:
	_controlled_avatar = p_avatar

##解绑avatar
func unbind_avatar() -> void:
	_controlled_avatar = null

##解绑avatar
func get_avatar() -> Player:
	return _controlled_avatar

##删除Avatar
func free_avatar() ->void:
	if _controlled_avatar:
		_controlled_avatar.queue_free()

func _physics_process(delta: float) -> void:
	if _controlled_avatar == null:
		return

	move_input = Input.get_vector(
		"move_left",
		"move_right",
		"move_up",
		"move_down"
	)

	_controlled_avatar.set_move_input(move_input)

##获取输入并通知avatar
func _unhandled_input(event: InputEvent) -> void:
	if _controlled_avatar == null or event.is_echo():
		return

	if event.is_action_pressed(&"jump"):
		_controlled_avatar.press_jump()
	elif event.is_action_released(&"jump"):
		_controlled_avatar.release_jump()

	#if event.is_action_pressed(&"dash"):
		#_controlled_avatar.press_dash()

	if event.is_action_pressed(&"climb"):
		_controlled_avatar.press_climb()
	elif event.is_action_released(&"climb"):
		_controlled_avatar.release_climb()

	if event.is_action_pressed(&"grap_hook"):
		_controlled_avatar.press_grap_hook()
	elif event.is_action_released(&"grap_hook"):
		_controlled_avatar.release_grap_hook()
