using Godot;
using Mr.BrickAdventures;
using Mr.BrickAdventures.Autoloads;

namespace Mr.BrickAdventures.scripts.Events;

[GlobalClass]
public partial class GhostEventHandler : Node
{
    public override void _Ready()
    {
        EventBus.Instance.LevelStarted += OnLevelStarted;
        EventBus.Instance.LevelCompleted += OnLevelCompleted;
    }

    public override void _ExitTree()
    {
        if (EventBus.Instance != null)
        {
            EventBus.Instance.LevelStarted -= OnLevelStarted;
            EventBus.Instance.LevelCompleted -= OnLevelCompleted;
        }
    }

    private void OnLevelStarted(int levelIndex, Node currentScene)
    {
        GD.Print($"GhostEventHandler: Level {levelIndex} started.");
        GhostManager.Instance.StartRecording(levelIndex);
        GhostManager.Instance.SpawnGhostPlayer(levelIndex, currentScene);
    }

    private void OnLevelCompleted(int levelIndex, Node currentScene, double completionTime)
    {
        GhostManager.Instance.StopRecording(true, completionTime);
    }
}