using System.Reflection.Emit;
using UnityEngine;
using System.Collections;

public class LevelScript : MonoBehaviour
{

    public AudioClip music;
    public AudioClip gameOver;
    public AudioClip fastMusic;
    public AudioClip victoryMusic;
    public int remainingEnemies;
    public int nextLevel;
    public GameState state = GameState.Normal;
    public Font msgFont;
    private string msg;
    private GUIStyle msgStyle;

    public enum GameState
    {
        Normal,
        Win,
        Lose,
        Hit
    };
	// Use this for initialization
	void Start ()
	{
        msgStyle = new GUIStyle();
	    msgStyle.normal.textColor = Color.white;
	    msgStyle.font = msgFont;
       
        msgStyle.alignment = TextAnchor.MiddleCenter;
	    GetComponent<AudioSource>().clip = music;
        GetComponent<AudioSource>().Play();
	    msg = "";
	}

    void ResetLevel()
    {
        Application.LoadLevel(nextLevel-1);
    }

    void GoToNextLevel()
    {
        GetComponent<AudioSource>().clip = null;
        Application.LoadLevel(nextLevel);
    }

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

	    if (PlayerScript.ammoCount == 1 && GetComponent<AudioSource>().clip != fastMusic)
	    {
            GetComponent<AudioSource>().Stop();
            GetComponent<AudioSource>().clip = fastMusic;
            GetComponent<AudioSource>().Play();
	    }
        if (PlayerScript.ammoCount == 0 && GetComponent<AudioSource>().clip != gameOver && remainingEnemies!= 0)
        {
            state = GameState.Lose;
            GetComponent<AudioSource>().Stop();
            GetComponent<AudioSource>().clip = gameOver;
            GetComponent<AudioSource>().Play();
            Invoke("ResetLevel",5);
        }
	    if (remainingEnemies == 0 && GetComponent<AudioSource>().clip != victoryMusic)
	    {
            state = GameState.Win;
	        GetComponent<AudioSource>().Stop();
            GetComponent<AudioSource>().clip = victoryMusic;
            GetComponent<AudioSource>().Play();

            Invoke("GoToNextLevel", 5);
	    }
	}

    void SwitchToNormal()
    {
        state = GameState.Normal;
        msg = "";
    }

    void OnGUI()
    {
       
        switch (state)
        {
                case GameState.Normal:
                break;
                case GameState.Win:
                    msg = "You Win!\n Loading Level " + nextLevel + " .";
                    Invoke("SwitchToNormal",5);
                    break;
                case GameState.Lose:
                    msg = "You Lost.\n Restarting Level " + (nextLevel - 1) + " .";
                    Invoke("SwitchToNormal", 5);
                    break;
                case GameState.Hit:
                    msg = "Hit.\n Only " + remainingEnemies + " enemies remain.";
                    Invoke("SwitchToNormal", 2);
                    break;
        }

        GUI.Label(new Rect(0, 0, Screen.width, Screen.height), msg, msgStyle);
    }
}
