class_name Player extends CharacterBody3D

@export var walk_speed: float = 4.0
@export var run_speed: float = 6.0

@onready var input = $Input
@onready var interactor = $Interactor

var is_running: bool:
    get: return velocity and input.is_running

var is_carrying_item = true
var is_weapon_ready: bool:
    get: return is_carrying_item and input.is_weapon_ready

func _ready() -> void:
    input.connect('interact', _on_interact)
    input.connect('fire', _on_fire)

func _physics_process(delta: float) -> void:
    if is_weapon_ready:
        rotate_toward_look(delta)
    else:
        move_and_rotate(delta)

func move_and_rotate(_delta: float):
    var speed = run_speed if input.is_running else walk_speed
    velocity = input.next_velocity(speed)
    if !velocity.is_zero_approx():
        look_at(global_position + velocity, Vector3.UP, true)
    move_and_slide()

func rotate_toward_look(_delta: float):
    velocity = Vector3.ZERO
    var target = input.get_look_target(global_position)
    if target.is_some():
        look_at(target.unwrap(), Vector3.UP, true)

func _on_interact():
    interactor.interact_nearest()

func _on_fire():
    if is_weapon_ready:
        print('firing weapon')

func on_save():
    return {
        position = position,
        rotation = rotation
    }

func on_before_load():
    pass

func on_load(data: Dictionary):
    position = data.position
    rotation = data.rotation
