using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Countdown : MonoBehaviour
{

    public float seconds = 3;
    public bool lockControls = true;
    public AudioClip tickSound;
    public AudioClip startSound;
    public AudioSource audioSource;
    public GameObject[] enableOnZero;
    public GameObject[] disableOnZero;
    public string finalText = "Go!";
    public float finalTextScreentime = 0.5f;    //How long should we display the final text
    public Text uiText;

    public float remaining;

    // Start is called before the first frame update
    void Start()
    {
        if (this.lockControls)
        {
            GameObject.FindGameObjectWithTag("GameManager").GetComponent<GameManager>().LockControls(this.seconds);
        }

        this.remaining = this.seconds;
    }

    // Update is called once per frame
    void Update()
    {
        int second = (int)Mathf.Ceil(this.remaining);
        this.UpdateText(second);
        

        if(this.remaining <= 0)
        {
            this.ProcessGameObjects(this.enableOnZero, true);
            this.ProcessGameObjects(this.disableOnZero, false);
        }

        if(this.remaining <= -finalTextScreentime)
        {
            this.uiText.gameObject.SetActive(false);
            this.enabled = false;
        }

        this.remaining -= Time.deltaTime;
    }

    private void UpdateText(int second)
    {
        string newText = this.remaining > 0 ? second.ToString() : this.finalText;

        if(newText != this.uiText.text)
        {
            this.uiText.text = newText;
            this.audioSource.PlayOneShot(newText == this.finalText ? this.startSound : this.tickSound);
        }
    }

    private void ProcessGameObjects(GameObject[] objectList, bool enable)
    {
        for (int i = 0; i < objectList.Length; i++)
        {
            objectList[i].SetActive(enable);
        }
    }
}
