extends CanvasLayer
class_name ShipTutorial

const DEFAULT_OBJECT_ACCELERATION = Vector2(1,0)

@export var object_3d : Node3D
@export var ok_button : Button
@export var animation_player : AnimationPlayer
@export var player : Player3D
@export var tutorial_name := "ship"

signal disappeared

var object_acceleration := Vector2(0,0)

var rotating := false

var prev_mouse_pos : Vector2
var next_mouse_pos : Vector2

func _ready():
    hide()
    ok_button.button_down.connect(_on_ok_button_button_down)

func appear():
    AudioManager.play_sfx("Unlock_tool")
    animation_player.play("appear")
    Input.mouse_mode = Input.MOUSE_MODE_VISIBLE
    player.controlling_player=false
    Pointer.action_disabled = true

func _process(delta):
    update_rotation(delta)

func update_rotation(delta):
    if visible:
        next_mouse_pos = get_viewport().get_mouse_position()
        if Input.is_action_just_pressed("action"):
            rotating = true
            prev_mouse_pos = get_viewport().get_mouse_position()
        if Input.is_action_just_released("action"):
            rotating = false
            object_acceleration = Vector2(
                float(next_mouse_pos.x - prev_mouse_pos.x),
                float(next_mouse_pos.y - prev_mouse_pos.y)
            )

        var object_rotation = object_acceleration

        if rotating:
            object_rotation = Vector2(
                float(next_mouse_pos.x - prev_mouse_pos.x),
                float(next_mouse_pos.y - prev_mouse_pos.y)
            )
            prev_mouse_pos = next_mouse_pos
        else :
            object_acceleration = object_acceleration.lerp(DEFAULT_OBJECT_ACCELERATION, 0.1)

        object_3d.rotate(Vector3.UP, object_rotation.x * delta)
        object_3d.rotate(Vector3.RIGHT, object_rotation.y * delta)


func _on_ok_button_button_down():
    animation_player.play_backwards("appear")
    disappeared.emit()
    Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
    player.controlling_player = true
    GameInfo.game_data.tutorials_done.append(tutorial_name)
    get_tree().create_timer(0.2).timeout.connect( # Put a delay to not interfere with the ok button click
        func():
            Pointer.action_disabled = false
    )
