extends Node

signal player_spawned(player: Player)
signal player_dead(player: Player)

var _cached_player_controller: PlayerController
var _cached_player: Player

var _camera_follower : Node = null

## player controller進入tree會注冊自己到Global
func register_player_controller(pc: PlayerController) -> PlayerController:
	if not pc: return null
	
	_cached_player_controller = pc
	return _cached_player_controller

## player進入tree會注冊自己到Global
func register_player(player: Player) -> Player:
	if not player: return null
	
	_cached_player = player
	
	##如果我们缓存了一个camera_follower,在玩家重生的时候我们会让follower自动绑定
	if _camera_follower:
		_camera_follower.register_follower(_cached_player)
	return _cached_player

## 外部快速获取Player
func get_player() -> Player:
	return _cached_player

## 外部快速获取Player Controller
func get_player_controller() -> PlayerController:
	return _cached_player_controller

func player_follow_camera() -> void:
	var cam := ReedCameraSystem.get_current_camera_pointer() as CameraPointer
	if not cam:return
	
	var follower := cam.get_tool_by_type(CameraPointer.ToolType.FOLLOWER)
	if not follower:return
	
	_camera_follower = follower
	
	if not _cached_player:return
	follower.register_follower(_cached_player)

func player_unfollow_camera() -> void:
	if _camera_follower:
		_camera_follower.unregister_follower()
		_camera_follower = null

## 外部用于监听Player死亡
func boradcast_player_dead_event(player:Player) -> void:
	player_dead.emit(player)
