extends CharacterBody3D


var SPEED = 20
var JUMP_VELOCITY = 8

@onready var arm: Node3D = $arm
@onready var model: Node3D = $model

# GESTION CAMERA --------------------------
@onready var spring_arm: SpringArm3D = $arm/SpringArm3D
@onready var camera: Camera3D = $arm/SpringArm3D/Camera3D
@onready var camera_pov: Camera3D = $Camera3D_POV
var third_person : bool = true

@onready var sprite_tuto: Sprite3D = $SpriteTuto 
@onready var label_tuto: Label = $SpriteTuto/SubViewport/Label

@onready var audio_footstep: AudioStreamPlayer3D = $Audio_Footstep
var footstep_sounds: Array[AudioStream] = [
	preload("res://assets/audio/footsteps/dirt_step_1.wav"),
	preload("res://assets/audio/footsteps/dirt_step_2.wav"),
	preload("res://assets/audio/footsteps/dirt_step_3.wav"),
	preload("res://assets/audio/footsteps/dirt_step_4.wav")
]
var footstep_timer: float = 0.0
const FOOTSTEP_DELAY: float = 0.15

@onready var pause: Control = $pause

var can_play : bool = true


func _ready():
	Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
	label_tuto.text = Sauvegarde.get_text("tuto_1")
	
	if third_person:
		camera.make_current()
	else:
		camera_pov.make_current()
		model.visible = false
	
func _input(_event):
	if Input.is_action_just_pressed("ui_cancel"):
		if !get_tree().paused:
			pause.pause()
		else:
			pause.resume()
					
		
func _physics_process(delta: float) -> void:
	# Add the gravity.
	if not is_on_floor():
		velocity += get_gravity() * delta

	# Handle jump
	if Input.is_action_just_pressed("ui_accept") and is_on_floor():
		velocity.y = JUMP_VELOCITY

	# Get the input direction and handle the movement/deceleration.
	var input_dir := Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down")
	var direction := (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
	if direction:
		velocity.x = direction.x * SPEED
		velocity.z = direction.z * SPEED
	else:
		velocity.x = move_toward(velocity.x, 0, SPEED)
		velocity.z = move_toward(velocity.z, 0, SPEED)

	# footstep sounds
	if is_on_floor() and Vector2(velocity.x, velocity.z).length() > 0.5:
		footstep_timer -= delta
		if footstep_timer <= 0.0:
			play_random_footstep()
			footstep_timer = FOOTSTEP_DELAY
	else:
		footstep_timer = 0.0	

	if can_play:
		move_and_slide()
		

func play_random_footstep( pitch=[0.85, 1.15] ) -> void:
	var random_index = randi() % footstep_sounds.size()
	audio_footstep.stream = footstep_sounds[random_index]
	
	audio_footstep.pitch_scale = randf_range( pitch[0], pitch[1] )
	audio_footstep.play()
