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

public class GameManager : MonoBehaviour
{
    [SerializeField]
    private float gameLengthInSeconds = 60f;

    [SerializeField]
    private Text scoreText;

    [SerializeField]
    private Text timerText;

    [SerializeField]
    private GameObject gameStateUI;


    [SerializeField]
    private AudioClip startGameChime;

    [SerializeField]
    private AudioClip endGameChime;

    private AudioSource gameStateSounds;

    public static bool gameStarted = false;


    public static int score;
    private float timer;
    private Text gameStateText;
    private Animator gameStateTextAnim;

    // Start is called before the first frame update
    void Start()
    {
        gameStateText = gameStateUI.GetComponent<Text>();
        gameStateText.text = "Hit Space To Play!";

        gameStateTextAnim = gameStateUI.GetComponent<Animator>();
        gameStateTextAnim.SetBool("ShowText", true);

        gameStateSounds = GetComponent<AudioSource>();

        timer = gameLengthInSeconds;

        UpdateScoreBoard(); 
    }

    // Update is called once per frame
    void Update()
    {
        //If the game has not started and player presses the space key.....
        if(!gameStarted && Input.GetKeyDown(KeyCode.Space))
        {
            //....Then start the game
            StartGame();
        }

        //If the game has started
        if (gameStarted)
        {
            //....Decrement the timer
            timer -= Time.deltaTime;

            UpdateScoreBoard();
        }

        //If the gameis running and player is out of time....
        if(gameStarted && timer <= 0)
        {
            //...Then end the game..
            EndGame();
        }

        //Escape to end the game application.....
        if(Input.GetKeyDown(KeyCode.Escape))
        {
            Application.Quit();
        }
    }

    private void UpdateScoreBoard()
    {
        scoreText.text = score + " Targets";

        timerText.text = Mathf.RoundToInt(timer) + " Seconds";

    }

    private void StartGame()
    { 
        score = 0;
        gameStarted = true;
        gameStateTextAnim.SetBool("ShowText", false);

        gameStateSounds.clip = startGameChime;
        gameStateSounds.Play();
    }

    private void EndGame()
    {
        gameStateText.text = "Game Over!\nHit Space To Restart!";
        gameStateTextAnim.SetBool("ShowText", true);
        gameStarted = false;
        timer = gameLengthInSeconds;

        gameStateSounds.clip = endGameChime;
        gameStateSounds.Play();
    }
}