class_name PlayerManager extends Node3D

const P2_CAMERA_SENSITIVITY: Vector2 = Vector2(3.0, 2.0)

@export var player_id: int = 1

var _spawned: Player

@onready var player_scene: PackedScene = load("res://src/player/player.tscn")

@onready var crosshair: Crosshair = get_tree().get_nodes_in_group("CrosshairGroup")[player_id - 1]
@onready
var overlay: OverlayEffects = get_tree().get_nodes_in_group("OverlayEffectsGroup")[player_id - 1]
@onready var heat_meter: ProgressBar = get_tree().get_nodes_in_group("HeatMeterGroup")[player_id - 1]
@onready
var damage_meter: ProgressBar = get_tree().get_nodes_in_group("DamageMeterGroup")[player_id - 1]
@onready var structure_meter: StructureMeter = get_tree().get_nodes_in_group("StructureMeterGroup")[
	player_id - 1
]


func _ready() -> void:
	respawn()


func get_player_viewport() -> SubViewport:
	return (
		get_tree().get_first_node_in_group("Viewport1" if player_id == 1 else "Viewport2")
		as SubViewport
	)


# TODO terrible pattern. clean up when it isn't 4AM lmao


func _unhandled_input(event: InputEvent) -> void:
	if _spawned and player_id == 1 and event is InputEventMouseMotion:
		_spawned.camera_root.camera_motion((event as InputEventMouseMotion).relative)


func _physics_process(_delta: float) -> void:
	if _spawned and player_id != 1:
		_spawned.camera_root.camera_motion(
			(
				Input.get_vector("camera_left", "camera_right", "camera_up", "camera_down")
				* P2_CAMERA_SENSITIVITY
			)
		)


func get_input_vector() -> Vector2:
	if player_id == 1:
		return Input.get_vector("left", "right", "forward", "backward")
	return Input.get_vector("left_2", "right_2", "forward_2", "backward_2")


func jump_action() -> String:
	if player_id == 1:
		return "jump"
	return "jump_2"


func boost_action() -> String:
	if player_id == 1:
		return "boost"
	return "boost_2"


func weapon_action() -> String:
	if player_id == 1:
		return "weapon_trigger"
	return "weapon_trigger_2"


func respawn() -> void:
	if _spawned:
		_spawned.queue_free()
	_spawned = player_scene.instantiate()
	_spawned.manager = self
	if player_id == 1:
		_spawned._equipment = MechCharacter.Equipment.RIFLE
	else:
		_spawned._equipment = MechCharacter.Equipment.AUTOCANNON

	var viewport: SubViewport = get_player_viewport()
	viewport.add_child(_spawned)
	_spawned.reparent(viewport)

	_spawned.global_position = global_position
	_spawned.global_rotation = global_rotation
