using Godot;
using Mr.BrickAdventures.Autoloads;
using Mr.BrickAdventures.scripts.State;

namespace Mr.BrickAdventures.scripts.Events;

/// <summary>
/// Handles game events and updates statistics accordingly.
/// </summary>
public partial class StatisticsEventHandler : Node
{
    public override void _Ready()
    {
        EventBus.Instance.CoinCollected += OnCoinCollected;
        EventBus.Instance.EnemyDefeated += OnEnemyDefeated;
        EventBus.Instance.PlayerDied += OnPlayerDied;
        EventBus.Instance.LevelCompleted += OnLevelCompleted;
        EventBus.Instance.ChildRescued += OnChildRescued;
    }

    public override void _ExitTree()
    {
        if (EventBus.Instance == null) return;

        EventBus.Instance.CoinCollected -= OnCoinCollected;
        EventBus.Instance.EnemyDefeated -= OnEnemyDefeated;
        EventBus.Instance.PlayerDied -= OnPlayerDied;
        EventBus.Instance.LevelCompleted -= OnLevelCompleted;
        EventBus.Instance.ChildRescued -= OnChildRescued;
    }

    private void OnCoinCollected(int amount, Vector2 position)
        => GameStateStore.Instance?.IncrementStat(StatNames.CoinsCollected, amount);

    private void OnEnemyDefeated(Node enemy, Vector2 position)
        => GameStateStore.Instance?.IncrementStat(StatNames.EnemiesDefeated);

    private void OnPlayerDied(Vector2 position)
        => GameStateStore.Instance?.IncrementStat(StatNames.Deaths);

    private void OnLevelCompleted(int levelIndex, Node currentScene, double completionTime)
        => GameStateStore.Instance?.IncrementStat(StatNames.LevelsCompleted);

    private void OnChildRescued(Vector2 position)
        => GameStateStore.Instance?.IncrementStat(StatNames.ChildrenRescued);
}
