class_name Player
extends CharacterBody3D

@export var _input_mode: Inputer.Mode = Inputer.Mode.KB_MOUSE
@export var _device_index: int = -1

@export var _respawn_height: float = -5
@export var _collision_debug_material: Material

var movement: PlayerMovement = PlayerMovement.new()
var aiming: PlayerAiming = PlayerAiming.new()

var _respawn_point: Vector3
var _debug_collision_shapes := DebugCollisionShapes.new()

@onready var attack: PlayerAttack = $Attack


func _ready() -> void:
	_respawn_point = global_position
	Referencer.players.append(self)
	Referencer.players_count += 1
	_debug_collision_shapes.init(get_children(), self, _collision_debug_material)


func _process(_delta: float) -> void:
	call_deferred("_aiming")
	_process_respawning()

	var aim_pos := global_position + aiming.aim_offset
	Debugger.marker("aim", aim_pos + Vector3.UP)
	Debugger.vector("aimv", Vector3(aim_pos.x, 0, aim_pos.z), aim_pos + Vector3.UP)


func _physics_process(delta: float) -> void:
	if not is_multiplayer_authority():
		return

	var can_move := not attack.is_hitting()
	velocity = movement.movement(velocity, delta, is_on_floor(), can_move)

	move_and_slide()


func _unhandled_input(event: InputEvent) -> void:
	var mode := Inputer.get_event_mode(event)
	if not input_mode_is(mode):
		return

	movement.handle_input(event, mode)

	if event.is_action_pressed("attack"):
		attack.attack()


func input_mode_is(mode: Inputer.Mode) -> bool:
	return (
		(Referencer.players_count == 1 and mode == Inputer.mode)
		or (Referencer.players_count > 1 and _input_mode == mode)
	)


func _aiming() -> void:
	if input_mode_is(Inputer.Mode.CONTROLLER):
		aiming.controller_aiming(movement.move_input)

	if input_mode_is(Inputer.Mode.KB_MOUSE):
		var mouse_pos := get_viewport().get_mouse_position()
		aiming.mouse_aiming(mouse_pos, global_position, is_on_floor())

	if attack.is_hitting():
		return
	if aiming.aim_offset.length() > 0:
		look_at(global_position + aiming.aim_offset, Vector3.UP, true)


func _process_respawning() -> void:
	if global_position.y < _respawn_height:
		global_position = _respawn_point
		velocity = Vector3.ZERO
