using Codex.Events.Channels;
using Codex.Variables;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{ 
   [SerializeField] private IntVariableSO lives;
   [SerializeField] private int startingLives = 3;
   [SerializeField] private BoolVariableSO isPlaying;
   [SerializeField] private VoidEventChannelSO onLostLife;
   [SerializeField] private VoidEventChannelSO onRestart;
   [SerializeField] private VoidEventChannelSO onGameOver;
   
   private bool isInitialized = false;
   
   private void OnEnable()
   {
       onLostLife.OnEventRaised += LoseLife;
       onRestart.OnEventRaised += Restart;
   }
   
   private void OnDisable()
   {
       onLostLife.OnEventRaised -= LoseLife;
       onRestart.OnEventRaised -= Restart;
   }

   public void Start()
    {
        lives.SetValue(startingLives);

    }

    public void Update()
    {
        if (!isInitialized)
        {
            lives.SetValue(startingLives);
            isInitialized = true;
            isPlaying.SetValue(true);
        }
    }
   
    private void LoseLife()
    {
        if (lives.Value <= 0)
        {
            return;
        }
        
        lives.Add(-1);
        if (lives.Value <= 0)
        {
            isPlaying.SetValue(false);
            onGameOver.RaiseEvent();
        }
    }
    
    private void Restart()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        isInitialized = false;
    }
}
