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

public class MainMenuManager : MonoBehaviour {

    [SerializeField]
    int FADE_FRAMES;

    bool animating;
    bool fadeDone;

    bool getRekt;

    int getWrekt;


    // Use this for initialization
    void Start ()
    {
        animating = false;
        fadeDone = false;
        getRekt = false;
        getWrekt = 0;
        StartCoroutine(FadeIn());
    }

    // Update is called once per frame
    void Update()
    {
        if (!animating)
        {
            if (Input.GetKeyDown(KeyCode.JoystickButton0))
            {
                getWrekt = 1;
                StartCoroutine(FadeAndLoad());
            }
            else if (Input.GetKeyDown(KeyCode.JoystickButton1))
            {
                getWrekt = 3;
                StartCoroutine(FadeAndLoad());
            }
            else if (Input.GetKeyDown(KeyCode.JoystickButton7))
            {
                getWrekt = 2;
                StartCoroutine(FadeAndLoad());
            }
        }

        if(getRekt)
        {
            if(getWrekt == 1)
            {
                SceneManager.LoadScene("Game");
            }
            else if(getWrekt == 2)
            {
                SceneManager.LoadScene("Controls");
            }
            else if(getWrekt == 3)
            {
                Application.Quit();
            }
        }
    }

    IEnumerator FadeIn()
    {
        //animating = true;
        for (int i = 0; i < FADE_FRAMES; ++i)
        {
            gameObject.GetComponent<Image>().color = new Color((float)i / FADE_FRAMES, (float)i / FADE_FRAMES, (float)i / FADE_FRAMES, 1.0f);
            yield return null;
        }
        yield return new WaitForFixedUpdate();
        //animating = false;
    }

    IEnumerator FadeAndLoad()
    {
        Debug.Log("Start FadeAndLoad");
        //animating = true;
        for (int i = 0; i < FADE_FRAMES; ++i)
        {
            Debug.Log("I = " + i + "Numbers = " + (1.0f - ((float)i / FADE_FRAMES)));
            gameObject.GetComponent<Image>().color = new Color(1.0f - ((float)i / FADE_FRAMES), 1.0f - ((float)i / FADE_FRAMES), 1.0f - ((float)i / FADE_FRAMES), 1.0f);
            yield return null;
        }
        yield return new WaitForFixedUpdate();
        //animating = false;
        //fadeDone = true;

        yield return new WaitForSeconds(0.5f);
        StartCoroutine(LoadAsync());
    }

    IEnumerator LoadAsync()
    {
        getRekt = false;
        yield return new WaitForSeconds(0.2f);
        getRekt = true;

    }
}
