using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameController : MonoBehaviour
{
    public GameObject[] spawnPoints;
    public GameObject[] obstructionPrefabs;
    public TrafficCircle trafficCircle;
    public RoadSign roadSign;

    private bool gameOver;




    void Awake()
    {
        Messenger<string>.AddListener("GameOverFailure", OnGameOverFailure);
        Messenger.AddListener("GameOverGoalReached", OnGameOverGoalReached);
    }

    void Start()
    {
        gameOver = false;
        StartCoroutine(ObstructionSpawner());
        StartCoroutine(MangeRoadStatus());
    }

    void OnDestroy()
    {
        Messenger<string>.RemoveListener("GameOverFailure", OnGameOverFailure);
        Messenger.RemoveListener("GameOverGoalReached", OnGameOverGoalReached);
    }

    IEnumerator ObstructionSpawner()
    {
        //Debug.Log("ObstructionSpawner");
        yield return new WaitForSeconds(0.8f);
        SpawnObstruction();
        if (!gameOver)
        {
            StartCoroutine(ObstructionSpawner());
        }
    }

    IEnumerator MangeRoadStatus()
    {
        while(!gameOver)
        {
            yield return new WaitForSeconds(Random.Range(6.5f, 12.5f));
            roadSign.SetEndRoadWork();
            trafficCircle.OpenExits();

            yield return new WaitForSeconds(Random.Range(4.5f, 15.5f));
            roadSign.SetRoadWorkAhead();
            trafficCircle.CLoseExits();
        }        
    }

    void SpawnObstruction()
    {
        //Debug.Log("Spawn obstruction");

        
        var spawnPoint = spawnPoints[Random.Range(0, spawnPoints.Length)];
        
        var obstruction = GameObject.Instantiate(
            obstructionPrefabs[Random.Range(0, obstructionPrefabs.Length)]
        );

        obstruction.transform.position = spawnPoint.transform.position;
        obstruction.transform.parent = trafficCircle.gameObject.transform;
    }

    void OnGameOverFailure(string message)
    {
        // Top all coroutines
        // Transition? UI UPDATE?
        gameOver = true;
        StopAllCoroutines();
    }

    void OnGameOverGoalReached()
    {
        gameOver = true;
        StopAllCoroutines();
    }

    public void Replay()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }
}
