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

public class Game05 : MonoBehaviour{

    public string menuScene;
    public string[] scenes;
    public Image timeBar;
    public float maxTime;
    float currentTime;
    [Space(10)]
    public GameObject death1;
    public GameObject death2;
    public GameObject particles;
    public RawImage water;
    bool finish;
    bool lost;

    // Start is called before the first frame update
    void Start(){
        currentTime = maxTime;
        water.transform.localScale = new Vector2(water.transform.localScale.x, 0);
        particles.SetActive(false);
    }

    // Update is called once per frame
    void Update(){
        if (Input.GetKey(KeyCode.Space)){
            water.transform.localScale = new Vector2(water.transform.localScale.x, water.transform.localScale.y + (.5f * Time.deltaTime));
            particles.SetActive(true);
        }
        if (Input.GetKeyUp(KeyCode.Space)){
            particles.SetActive(false);
        }
        if (finish){
            if(water.transform.localScale.y < .77f){
                StartCoroutine(Death2());
                death2.SetActive(true);
            }else if(water.transform.localScale.y >= .77f && water.transform.localScale.y < .95f){
                CompleteLevel();
            }
        }else if(water.transform.localScale.y >= .95f && !lost){
            StartCoroutine(Death1());
            death1.SetActive(true);
            lost = true;
        }
        currentTime -= 1 * Time.deltaTime;
        timeBar.transform.localScale = new Vector2(currentTime / maxTime, timeBar.transform.localScale.y);
        if (currentTime <= 0){
            finish = true;
        }
    }

    IEnumerator Death1(){
        yield return new WaitForSecondsRealtime(1f);
        AudioManager.instance.Play("Water");
        Time.timeScale = 0;
        yield return new WaitForSecondsRealtime(3f);
        LoseGame();
    }

    IEnumerator Death2(){
        yield return new WaitForSecondsRealtime(1f);
        Time.timeScale = 0;
        yield return new WaitForSecondsRealtime(3f);
        LoseGame();
    }

    public void CompleteLevel(){
        string scene = scenes[Random.Range(0, scenes.Length - 1)];
        LevelLoader.Instance.LoadLevel(scene);
    }

    public void LoseGame(){
        Debug.LogError(SceneManager.GetActiveScene().name);
        LevelLoader.Instance.LoadLevel(menuScene);
    }
}
