using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;

public class GameManager : MonoBehaviour
{

    [SerializeField] GameObject coinPrefab;
    int coinCounter = 0;
    [SerializeField] TextMeshProUGUI coinCounterText;
    [SerializeField] TextMeshProUGUI countdownText;
    [SerializeField] TextMeshProUGUI gameOverText;
    GameObject player;
    int timer = 59;

    public void UpdateCoinCounter()
    {
        coinCounter++;
        coinCounterText.SetText("Coins: " + coinCounter.ToString());

        if (coinCounter > 4)
        {
            GameOver(true);
        }

    }

    public void SpawnNewCoin()
    {
        float randX = Random.Range(-20.0f, 20.0f);
        float randZ = Random.Range(-20.0F, 20.0f);
        Instantiate(coinPrefab,
            new Vector3(randX, 3.0f, randZ),
            coinPrefab.transform.rotation);

        UpdateCoinCounter();
    }

    void GameOver(bool isGameWin)
    {
        if(isGameWin)
        {
            gameOverText.SetText("You Won! :)");
        }

        player.GetComponent<CharacterController>().enabled = false;
        gameOverText.gameObject.SetActive(true);
    }

    IEnumerator Countdown()
    {
        while (timer > 0)
        {
            yield return new WaitForSeconds(1.0f);
            timer--;
            countdownText.SetText("0:" + timer.ToString());
        }

        GameOver(false);
    }

    // Start is called before the first frame update
    void Start()
    {
        player = GameObject.Find("Player");
        gameOverText.gameObject.SetActive(false);
        StartCoroutine(Countdown());
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
