﻿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;
	    audio.clip = music;
        audio.Play();
	    msg = "";
	}

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

    void GoToNextLevel()
    {
        audio.clip = null;
        Application.LoadLevel(nextLevel);
    }

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

	    if (PlayerScript.ammoCount == 1 && audio.clip != fastMusic)
	    {
            audio.Stop();
            audio.clip = fastMusic;
            audio.Play();
	    }
        if (PlayerScript.ammoCount == 0 && audio.clip != gameOver && remainingEnemies!= 0)
        {
            state = GameState.Lose;
            audio.Stop();
            audio.clip = gameOver;
            audio.Play();
            Invoke("ResetLevel",5);
        }
	    if (remainingEnemies == 0 && audio.clip != victoryMusic)
	    {
            state = GameState.Win;
	        audio.Stop();
            audio.clip = victoryMusic;
            audio.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);
    }
}
