# ---------------------------------------------------------------------
# This script is supposed to control the node that is rendered on the 
# client side, and send the changes to the server node
# ---------------------------------------------------------------------
extends Node3D
class_name PlayerNode

var jumping: bool = false
var shooting: bool = false
var moving: bool = false
var look_dir: Vector2
var input_direction: Vector2
var camera_sens: float = 0.002

const JUMP_VELOCITY = 4.5
var character_speed: int = 5

var controlled_node: ServerNode = null
@export var owner_id: int

@onready var shared_node: CharacterBody3D = $SharedNode
@onready var camera_mount: Node3D = $SharedNode/CameraMount
@onready var camera: Camera3D = $SharedNode/CameraMount/Camera3D
var hud: Hud
var hud_camera: Camera3D
var gun_mount: Node3D
const DEFAULT_WEAPON := "ak"
var first_slot_weapon: WeaponController

func _ready() -> void:
	set_multiplayer_authority(multiplayer.get_unique_id())
	shared_node.set_collision_layer_value(2, true)
	shared_node.set_collision_mask_value(1, true)
	shared_node.set_collision_mask_value(2, true)
	camera.make_current()
	var hud_scene: PackedScene = ResourceLoader.load("res://scenes/player/hud.tscn")
	hud = hud_scene.instantiate()
	camera.add_child(hud)
	hud_camera = hud.camera
	gun_mount = hud.gun_mount
	_load_weapon()
	#for child in controlled_node.find_child("Model").find_children("*"):
		#if child is MeshInstance3D:
			#child.set_layer_mask_value(1, false)
	# Load the default weapon and set the current attack properties

func _load_weapon() -> void:
	var path_tmpl := "res://scenes/weapon/guns/%s/with_hands.tscn"
	var path := path_tmpl % DEFAULT_WEAPON
	var scene: PackedScene = ResourceLoader.load(path)
	var node: WeaponController = scene.instantiate()
	first_slot_weapon = node
	for child in node.find_children("*"):
		if child is MeshInstance3D:
			child.set_layer_mask_value(1, false)
	#first_slot_weapon.position = Vector3(-1, -1, -1)
	hud.find_child("GunMount").add_child(first_slot_weapon)
	
	
func initial_position_sync():
	shared_node.global_position = controlled_node.shared_node.global_position
	shared_node.rotation = controlled_node.shared_node.rotation

func _input(event):
	if multiplayer.get_unique_id() == get_multiplayer_authority():
		if Input.is_action_just_pressed("jump"): jump()
		
		if event is InputEventMouseMotion and Input.mouse_mode == Input.MOUSE_MODE_CAPTURED:
			look_dir = event.relative * 1
			shared_node.rotation.y -= look_dir.x * camera_sens * 1.0
			camera_mount.rotation.x = clamp(camera_mount.rotation.x - look_dir.y * camera_sens * 1.0, -1.5, 1.5)
			controlled_node.set_rotation_x.rpc_id(1, camera_mount.rotation.x)
			controlled_node.set_rotation_y.rpc_id(1, shared_node.rotation.y)
		
		input_direction = Input.get_vector("move_left", "move_right", "move_forward", "move_backward")
		controlled_node.set_input_direction.rpc_id(1, input_direction)
		
		if Input.is_action_just_pressed("shoot"): shooting = true
		if Input.is_action_just_released("shoot"): shooting = false

func jump():
	jumping = true
	controlled_node.jump.rpc_id(1)

func _physics_process(delta: float) -> void:
	if multiplayer.get_unique_id() == get_multiplayer_authority():
		Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
		
		if not shared_node.is_on_floor():
			shared_node.velocity += shared_node.get_gravity() * delta
		if shared_node.is_on_floor() && jumping:
			shared_node.velocity.y = consts.DEFAULT_JUMP_VELOCITY
			
		#if shooting:
		jumping = false
		
		if shooting:
			controlled_node.shoot.rpc_id(1)
			first_slot_weapon.shoot()
			
		var direction := (shared_node.transform.basis * Vector3(input_direction.x, 0, input_direction.y)).normalized()
		if shared_node.is_on_floor():
			if direction:
				shared_node.velocity.x = direction.x * consts.DEFAULT_CHARACTER_SPEED
				shared_node.velocity.z = direction.z * consts.DEFAULT_CHARACTER_SPEED
			else:
				shared_node.velocity.x = move_toward(shared_node.velocity.x, 0, consts.DEFAULT_CHARACTER_SPEED)
				shared_node.velocity.z = move_toward(shared_node.velocity.z, 0, consts.DEFAULT_CHARACTER_SPEED)
		hud_camera.global_position = global_position


func _process(delta: float) -> void:
	shared_node.move_and_slide()

# -- This rpc should be called by the server in order to
# -- make the client send its position to the server
@rpc("any_peer", "call_local", "reliable")
func verify_position() -> void:
	var desired_position: Vector3 = shared_node.global_position
	controlled_node.send_position.rpc_id(1, desired_position)
	
@rpc("authority", "call_local")
func adjust_position(x: float, y: float, z: float):
	var new_position: Vector3 = Vector3(x, y, z)
	shared_node.global_position = new_position

@rpc("any_peer", "call_local", "reliable")
func verify_rotation() -> void:
	var desired_rotation: Vector3 = shared_node.global_rotation
	controlled_node.send_rotation.rpc_id(1, desired_rotation.x, desired_rotation.y, desired_rotation.z)
	
@rpc("authority", "call_local")
func adjust_rotation(x: float, y: float, z: float):
	var new_rotation: Vector3 = Vector3(x, y, z)
	shared_node.rotation = new_rotation
