using UnityEngine;
using UnityEngine.Events;

public class GameManager : MonoBehaviour
{
    public enum GameState
    {
        BuildingPath,
        BuildingTurrets,
        Level
    }
    
    [SerializeField] private Level[] _levels;
    [SerializeField] private SandPathBuildService _pathBuildService;
    [SerializeField] private UnityEvent<GameState> _onStateChanged;
    [SerializeField] private UnityEvent<Level> _onLevelChanged;

    public event UnityAction<GameState> OnStateChanged
    {
        add => _onStateChanged.AddListener(value);
        remove => _onStateChanged.RemoveListener(value);
    }

    public event UnityAction<Level> OnLevelChanged
    {
        add => _onLevelChanged.AddListener(value);
        remove => _onLevelChanged.RemoveListener(value);
    }

    private int _currentLvlIndex = -1;

    private GameState _currentState = GameState.BuildingPath;

    public GameState CurrentState
    {
        get => _currentState;
        set
        {
            _currentState = value;
            _onStateChanged?.Invoke(value);
        }
    }
    
    //public Level CurrentLevel => _levels[_currentLvlIndex];

    private void OnEnable()
    {
        _pathBuildService.OnBuildComplete += OnBuildComplete;
    }
    private void OnDisable()
    {
        _pathBuildService.OnBuildComplete -= OnBuildComplete;
    }

    private void OnBuildComplete()
    {
        CurrentState = GameState.BuildingTurrets;
    }

    public void NextLevel()
    {
        _currentLvlIndex = (_currentLvlIndex + 1) % _levels.Length;
        CurrentState = GameState.Level;
        _onLevelChanged?.Invoke(_levels[_currentLvlIndex]);
    }
}
