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

public class CanvasScript : MonoBehaviour
{
    [SerializeField]
    float p_myTimerBeforePlaying;

    GameObject p_myMenu;
    GameObject p_myInGame;
    GameObject p_myCredit;
    GameObject p_myEnd;
    [SerializeField]
    GameObject p_mySpaceShip;
    [SerializeField]
    AudioSource p_myAudioSource;
    [SerializeField]
    AudioSource p_myMenuAudio;
    [SerializeField]
    AudioSource p_myInGameAudio;
    [SerializeField]
    AudioSource p_myInfinityIntro;
    [SerializeField]
    AudioSource p_myInfinityLoop;
    [SerializeField]
    Text p_myText;

    bool Infinitybool;

    void Awake()
    {
        Time.timeScale = 1;
    }

    void Start ()
    {
        p_myMenuAudio.Play();
        p_myMenu = transform.GetChild(0).gameObject;
        p_myInGame = transform.GetChild(1).gameObject;
        p_myCredit = transform.GetChild(2).gameObject;
        p_myEnd = transform.GetChild(3).gameObject;
        p_myInGame.SetActive(false);
        p_myCredit.SetActive(false);
        p_myEnd.SetActive(false);
    }

    void Update()
    {
        if (Infinitybool && !p_myInfinityIntro.isPlaying && !p_myInfinityLoop.isPlaying)
        {
            p_myInfinityLoop.Play();
        }
    }

    public void StartGame()
    {
        Sound();
        p_myMenu.SetActive(false);
        p_mySpaceShip.GetComponent<SpaceShipScript>().setIsPlaying(true);
        HumanManager.setInfinity(false);
        StartCoroutine(AllowPlaying());
        p_myMenuAudio.Stop();
        p_myInGameAudio.Play();
    }

    public void Infinity()
    {
        Sound();
        p_myMenu.SetActive(false);
        p_mySpaceShip.GetComponent<SpaceShipScript>().setIsPlaying(true);
        HumanManager.setInfinity(true);
        StartCoroutine(AllowPlaying());
        p_myMenuAudio.Stop();
        p_myInfinityIntro.Play();
        Infinitybool = true;
    }

    public void Credits()
    {
        Sound();
        p_myMenu.SetActive(false);
        p_myCredit.SetActive(true);

        GameObject[] test = new GameObject[10];
    }

    public void Quit()
    {
        Sound();
        Application.Quit();
    }

    public void Back()
    {
        Sound();
        p_myEnd.SetActive(false);
        p_myCredit.SetActive(false);
        p_myMenu.SetActive(true);
    }

    IEnumerator AllowPlaying()
    {
        yield return new WaitForSeconds(p_myTimerBeforePlaying);
        p_myInGame.SetActive(true);
    }

    void Sound()
    {
        if (!p_myAudioSource.isPlaying)
        {
            p_myAudioSource.Play();
        }
    }

    public void End(string text)
    {
        p_myText.text = text;
        p_myInGame.SetActive(false);
        p_myEnd.SetActive(true);
    }

    public void Reload()
    {
        Application.LoadLevel(Application.loadedLevel);
    }
}