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

extends CharacterBody3D

@export var jumping := false 
var shooting := false
@export var input_direction := Vector2()

@onready var camera_mount = $CameraMount
@onready var camera = $CameraMount/Camera3D
@onready var placeholder: Node3D = $'..'
var paused := false
const JUMP_VELOCITY = 4.5


#func _ready() -> void:
var current_gun: String = "ak"
@onready var gun_mount: Node3D = $CameraMount/Camera3D/HUD/SubViewportContainer/SubViewport/Camera3D/GunMount
@onready var gun_mount_anim: AnimationPlayer = $CameraMount/Camera3D/HUD/SubViewportContainer/SubViewport/Camera3D/GunMount/AnimationPlayer
var gun_with_hands: Node3D = null
@onready var bullet_starting_point: Node3D = $CameraMount/BulletStartingPoint
@onready var aim_ray: RayCast3D = $CameraMount/BulletStartingPoint/AimRay
@onready var gun_camera: Camera3D = $CameraMount/Camera3D/HUD/SubViewportContainer/SubViewport/Camera3D
var current_weapon_damage: int
var current_weapon_bullet_speed: int
var current_weapon_cooldown_interwal: float
var look_dir: Vector2
var moving = false
func _ready() -> void:
	global_position = $"..".initial_position
	_add_legs_to_first_view()
	# -- TODO: It should not be hardcoded
	# Define a format string with placeholder '%s'
	var path_tmpl := "res://scenes/weapon/guns/%s/with_hands.tscn"
	var path := path_tmpl % current_gun
	var scene: PackedScene = ResourceLoader.load(path)
	var node: Node3D = scene.instantiate()
	node.scale = Vector3(0.5,0.5,0.5)
	node.position = Vector3(-0.3, -0.4, 0)
	current_weapon_bullet_speed = node.bullet_speed
	current_weapon_cooldown_interwal = node.cooldown
	current_weapon_damage = node.damage
	gun_with_hands = node
	gun_mount.add_child(node)

func _input(event):
	if multiplayer.get_unique_id() == get_multiplayer_authority():
		if Input.is_action_just_pressed("jump"): jumping = true
		if Input.is_action_just_pressed("shoot"): shooting = true
		if Input.is_action_just_released("shoot"): shooting = false
		if event is InputEventMouseMotion and Input.mouse_mode == Input.MOUSE_MODE_CAPTURED:
			look_dir = event.relative * 1
			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)
			server_node.set_rotation_y.rpc_id(1, rotation.y)
			server_node.set_rotation_x.rpc_id(1, -camera_mount.rotation.x)
			#server_node.set_input_direction.rpc_id(1, rotation.x, rotation.y)
		if Input.is_action_pressed("move_left") or Input.is_action_pressed("move_right") or Input.is_action_pressed("move_forward") or Input.is_action_pressed("move_backwards"):
			moving = true
		else:
			moving = false

@onready var server_node: PlayerServerNode = $"../ServerControlledNode"
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _physics_process(delta: float) -> void:	
	if multiplayer.get_unique_id() == get_multiplayer_authority():
		if !paused:
			Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
		input_direction = Input.get_vector("move_left", "move_right", "move_forward", "move_backwards")
		server_node.set_input_direction.rpc_id(1, input_direction)
		
		if not is_on_floor():
			velocity += get_gravity() * delta
		if is_on_floor() && jumping:
			server_node.jump.rpc_id(1)
			velocity.y = JUMP_VELOCITY
			
		if shooting:
			server_node.shoot.rpc_id(1)
		jumping = false
		
		var direction := (transform.basis * Vector3(input_direction.x, 0, input_direction.y)).normalized()
		if is_on_floor():
			if direction:
				#first_view_legs_anim.play("Run Forward")
				velocity.x = direction.x * placeholder.character_speed
				velocity.z = direction.z * placeholder.character_speed
			else:
				velocity.x = move_toward(velocity.x, 0, placeholder.character_speed)
				velocity.z = move_toward(velocity.z, 0, placeholder.character_speed)

func _process(delta: float) -> void:
	if moving:
		gun_mount_anim.play("move")
	else:
		gun_mount_anim.stop()
	move_and_slide()


var cant_shoot: bool = false
func _shoot():
	if not cant_shoot:
		gun_with_hands.shoot()
		cant_shoot = true
		await get_tree().create_timer(current_weapon_cooldown_interwal).timeout
		cant_shoot = false

#func _physics_process(delta: float) -> void:
	#if multiplayer.get_unique_id() == get_multiplayer_authority():
		#if not is_on_floor():
			#velocity += get_gravity() * delta
		#if is_on_floor() && jumping:
			#velocity.y = JUMP_VELOCITY
		#jumping = false
		#var direction := (transform.basis * Vector3(input_direction.x, 0, input_direction.y)).normalized()
		#if is_on_floor():
			#if direction:
				#velocity.x = direction.x * placeholder.character_speed
				#velocity.z = direction.z * placeholder.character_speed
			#else:
				#velocity.x = move_toward(velocity.x, 0, placeholder.character_speed)
				#velocity.z = move_toward(velocity.z, 0, placeholder.character_speed)
		#move_and_slide()
var first_view_legs_anim: AnimationPlayer = null
func _add_legs_to_first_view() -> Error :
	# -- TODO: It should not be hardcoded
	var path := "res://scenes/characters/blue/dummy.tscn"
	if not ResourceLoader.exists(path):
		return ERR_DOES_NOT_EXIST
	var scene: PackedScene = ResourceLoader.load(path)
	if not scene.can_instantiate():
		return ERR_CANT_OPEN
	var node: Node3D = scene.instantiate()
	var skeleton: Skeleton3D = node.find_child("Skeleton3D")
	var bone := skeleton.find_bone("mixamorig_Spine")
	if bone != -1:
		print(bone)
		skeleton.set_bone_pose_scale(bone, Vector3(0.0001, 0.0001, 0.0001))
	add_child(node)
	var animation_node: AnimationPlayer = node.find_child("AnimationPlayer")
	if animation_node != null:
		first_view_legs_anim = animation_node
	return OK

var camera_sens: float = 0.002

@rpc("authority", "reliable")
func set_current_rotation(rotation: Vector3):
	rotation = rotation

@rpc("any_peer", "reliable")
func set_current_position(x: float, y: float, z: float):
	global_position = Vector3(x, y ,z)

@rpc("any_peer", "call_local", "reliable")
func jump():
	jumping = true
