using UnityEngine;
using System.Collections;

public class Game : MonoBehaviour 
{

    public enum STATES
    {
        INVALID,
        MENU,
        LOADING_IN_PROGRESS,
        INITPLAY,
        PLAY,
        WINMENU,
        UPDATEWIN,
        FAIL
    };

    public class PlayerStats
    {
        public int currentLvl = 1;
    }

    public STATES state = STATES.MENU;

    public static Game instance;

    Levels levels;
    public GameObject herosPrefab;
    public Heros herosScript;

    //Interface
    public GameObject startInterface;
    public GameObject playingInterface;
    public GameObject WinInterface;
    public GameObject DieInterface;


    private float timer;
    private float startTime = 0;
    private int death = 0;

    public GameObject timeLabel;

    public GameObject lvl1_button;
    public GameObject lvl2_button;
    public GameObject lvl3_button;
    public GameObject lvl4_button;
    public GameObject lvl5_button;
    public GameObject quit_button;
    public GameObject mute_button;
    public GameObject die_button;
    public GameObject win_button;
    public GameObject[] labels;
    private UISprite[] buttons;

    Color32 buttonEnabled;
    Color32 buttonDisabled;

    private VortexEffect vortex;
    private Animator vortexAnimator;
    public AnimationClip clp;
    //
    public AudioClip[] audioClips;
    AudioSource[] music;
    private bool musicEnabled = true;
    private bool shakeBaby = false;

    int maxLevel;

    void Start()
    {
        instance = this;
        levels = GetComponent<Levels>();

        music = Camera.main.GetComponents<AudioSource>();
        vortex = Camera.main.GetComponent<VortexEffect>();
        vortexAnimator = Camera.main.GetComponent<Animator>();
        
        maxLevel = PlayerPrefs.GetInt("maxLevel", 5);
        buttonDisabled = new Color32(232, 222, 206, 255);
        buttonEnabled = new Color32(122, 0, 38, 255);

     
        UIEventListener.Get(lvl1_button).onClick += Lvl1;
        UIEventListener.Get(lvl2_button).onClick += Lvl2;
        UIEventListener.Get(lvl3_button).onClick += Lvl3;
        UIEventListener.Get(lvl4_button).onClick += Lvl4;
        UIEventListener.Get(lvl5_button).onClick += Lvl5;
        UIEventListener.Get(quit_button).onClick += Quit;
        UIEventListener.Get(mute_button).onClick += MusicToggle;
        UIEventListener.Get(die_button).onClick += Reload;
        UIEventListener.Get(win_button).onClick += Quit;

        buttons = new UISprite[maxLevel];

        buttons[0] = lvl1_button.GetComponentInChildren<UISprite>();
        buttons[1] = lvl2_button.GetComponentInChildren<UISprite>();
        buttons[2] = lvl3_button.GetComponentInChildren<UISprite>();
        buttons[3] = lvl4_button.GetComponentInChildren<UISprite>();
        buttons[4] = lvl5_button.GetComponentInChildren<UISprite>();

        for (int i = 0; i < PlayerPrefs.GetInt("lastLevel", 1); i++ )
        {
            string[] str = GetScore(i + 1).Split(',');
            ShowLvlScore(i + 1, str[0], str[1], str[2]);
        }

        foreach (UISprite s in buttons)
        {
            s.color = buttonDisabled;
        }

        EnableLvlButtons();

        playingInterface.SetActive(false);
        WinInterface.SetActive(false);
        DieInterface.SetActive(false);
    }

    void FixedUpdate()
    {
        if (Input.touchCount > 2)
        {
            PlayerPrefs.DeleteAll();
            EnableLvlButtons();
        }
        switch (state)
        {
            case STATES.INVALID: break;

            //case STATES.WINMENU:
                //break;

            case STATES.UPDATEWIN:
                Clear();
                int lvl = PlayerPrefs.GetInt("lastLevel", 1);


                string[] levelscore = GetScore(Levels.currentLevel).Split(',');
                if (float.Parse(levelscore[2]) < timer / (death+1)*1f)
                {
                    SaveScore(Levels.currentLevel, timer, death);
                    levelscore = GetScore(Levels.currentLevel).Split(',');
                    ShowLvlScore(Levels.currentLevel, levelscore[0], levelscore[1], levelscore[2]);
                }
                //else Debug.Log("Plus bas" + int.Parse(levelscore[2]) + " " + timer / (death + 1));

                foreach (string s in levelscore)
                {
                    Debug.Log(s);
                }


                if (Levels.currentLevel == lvl)
                {
                    Debug.Log(lvl);
                    lvl++;
                    PlayerPrefs.SetInt("lastLevel", lvl);
                    Debug.Log( "New lastlevel : " + PlayerPrefs.GetInt("lastLevel"));
                    //EnableLvlButtons();
                }
                playingInterface.SetActive(false);
                state = STATES.WINMENU;
                break;

            case STATES.FAIL:
                Clear();
                playingInterface.SetActive(false);
                break;
            
            case STATES.PLAY:
                CameraFollow();
                Timer();
                break;

            case STATES.MENU:
                startInterface.SetActive(true);
                playingInterface.SetActive(false);
                break;

            case STATES.INITPLAY:
                InitPlay();
                state = STATES.PLAY;
                break;
                
        }
    }

    void EnableLvlButtons()
    {
        int i = PlayerPrefs.GetInt("lastLevel", 1);
        Debug.Log("Activés : " + i);
        for (int j = 0; j < i; j++)
        {
            buttons[j].color = buttonEnabled;
            buttons[j].transform.parent.GetComponent<UIButton>().defaultColor = buttonEnabled;
        }
    }

    void OnGUI()
    {
        switch (state)
        {
            case STATES.INVALID: break;
            /*
            case STATES.WIN:
                {
                    GUI.Box(new Rect(Screen.width / 2 - 300, Screen.height / 2 - 50, 600, 100), "You win, bitch.");
                    if (GUI.Button(new Rect(Screen.width / 2 - 300, Screen.height / 2 +175, 600, 100), "Okay bro")) state = STATES.MENU;
                    break;
                }

            case STATES.FAIL:
                {
                    GUI.Box(new Rect(Screen.width / 2 - 300, Screen.height / 2 - 50, 600, 100), "You die, bitch.");
                    if (GUI.Button(new Rect(Screen.width / 2 - 300, Screen.height / 2 + 175, 600, 100), "Okay bro")) state = STATES.MENU;
                    break;
                }

            case STATES.MENU:
                {
                    //On affiche tous les boutons de 1 à maxLevel
                    for (int i = 1; i <= maxLevel; i++)
                    {
                        if (GUI.Button( MyRect(60, i* 150, 600, 100), "Level : " + i))
                        {
                            
                        }

                    }

                    if (GUI.Button(new Rect(50f, 50f, 150f, 100f), "Quitter")) Application.Quit();
                    //Au clic, on lance la méthode levels.LoadLevel(i);
                    break;
                }
             
            case STATES.LOADING_IN_PROGRESS:
                {
                    GUI.Label(new Rect(0, 0, 400, 300), "Loading In Progress...");
                    break;
                }
             */
        }
    }

    public void Victory()
    {
        state = STATES.UPDATEWIN;
        PlaySound(5);
        WinInterface.SetActive(true);
        
    }

    public void Fail()
    {
        state = STATES.FAIL;
        PlaySound(6);
        DieInterface.SetActive(true);
        death++;
    }

    void Clear()
    {
        DisableTD4W();
        foreach (Transform t in transform) Destroy(t.gameObject);
    }

    public void DestroyNumber(int num)
    {
        foreach (Transform t in transform)
        {
            if (t.name == num.ToString()) Destroy(t.gameObject);
        }
    }

    void CameraFollow()
    {
        Camera cam = Camera.main;
        cam.transform.position = new Vector3(herosScript.gameObject.transform.position.x, herosScript.gameObject.transform.position.y, - 10f);
    }

    static public Rect MyRect(float x, float y, float size_x, float size_y)
    {
        return new Rect(x*Screen.width / 1280,
                        y*Screen.height / 720,
                        size_x*Screen.width / 1280,
                        size_y*Screen.height / 720);
    }

    void Timer ()
    {
        timer = Time.time - startTime;
        timeLabel.GetComponent<UILabel>().text = "Temps : " + timer.ToString("000") + "\nMorts : " + death.ToString("00");
    }

    

    void InitPlay()
    {
        startInterface.SetActive(false);
        playingInterface.SetActive(true);
        timer = 0;
        startTime = Time.time;
    }

    void Lvl1(GameObject go)
    {
        LoadLvl(1);

    }

    void Lvl2(GameObject go)
    {
        LoadLvl(2);
    }

    void Lvl3(GameObject go)
    {
        LoadLvl(3);
    }

    void Lvl4(GameObject go)
    {
        LoadLvl(4);
    }

    void Lvl5(GameObject go)
    {
        LoadLvl(5);
    }

    void LoadLvl(int lvl)
    {
        Debug.Log(lvl + "<=" + PlayerPrefs.GetInt("lastLevel", 1));
        PlayerPrefs.SetInt("lastLevel", lvl);
        if (lvl <= PlayerPrefs.GetInt("lastLevel", 1))
        {
            Debug.Log("Passe");
            state = STATES.LOADING_IN_PROGRESS;
            levels.LoadLevel2(lvl);
            state = STATES.INITPLAY;
            PlaySound(lvl - 1);
        }
    }

    void Quit(GameObject go)
    {
        if (state != STATES.MENU)
        {
            DisableTD4W();
            Levels.checkpoint = false;
            if (DieInterface.activeInHierarchy) DieInterface.SetActive(false);
            else if (WinInterface.activeInHierarchy) WinInterface.SetActive(false);
            EnableLvlButtons();
            state = STATES.MENU;
            Clear();
        }
        else Application.Quit();
    }

    public void PlaySound(int i)
    {
        this.GetComponent<AudioSource>().clip = audioClips[i];
        this.GetComponent<AudioSource>().Play();
    }

    void Mute()
    {
        if (!music[1].isPlaying)
        {
            if (music[0].isPlaying)
            {
                Debug.Log("Paused");
                music[0].Pause();
            }
            else if (musicEnabled) music[0].Play();
        }
    }

    void MusicToggle(GameObject go)
    {
        musicEnabled = !musicEnabled;
        Mute();
    }

    public IEnumerator TurnDownForWhat()
    {
        
        if (!music[1].isPlaying)
        {
            shakeBaby = true;
            Mute();
            music[1].Play();
            vortexAnimator.Play("Vortex 0");
            yield return new WaitForSeconds(music[1].clip.length);
            music[0].Play();
            vortexAnimator.Play("Vortex");
            Debug.Log(music[1].clip.length);
            shakeBaby = false;
        }
    }

    void DisableTD4W()
    {
        if (shakeBaby)
        {
            StopCoroutine(TurnDownForWhat());
            music[1].Stop();
            music[0].Play();

            vortexAnimator.Play("Vortex");
            vortexAnimator.CrossFade("Vortex 0", 0.1f, -1, 0.0f);
            vortexAnimator.Play("Vortex");
            shakeBaby = false;
        }
    }

    void Reload(GameObject go)
    {
        DieInterface.SetActive(false);
        LoadLvl(Levels.currentLevel);
    }

    string GetScore(int lvl)
    {
        string scorestring = PlayerPrefs.GetString("Scores", "0,0,0;0,0,0;0,0,0;0,0,0;0,0,0");
        Debug.Log("load : " + scorestring);
        string[] levelScores = scorestring.Split(';');
        return levelScores[lvl - 1];
        
    }

    void SaveScore(int lvl, float t, int d)
    {
        string scorestring = PlayerPrefs.GetString("Scores", "0,0,0;0,0,0;0,0,0;0,0,0;0,0,0");
        string[] levelScores = scorestring.Split(';');
        string newlvlscore = t +","+ d + "," + t/(d+1);
        string newGlobalScore = "";
        for (int i = 0; i<levelScores.Length; i++)
        {
            if (i == lvl - 1) newGlobalScore += newlvlscore;
            else newGlobalScore += levelScores[i];
            if (i != levelScores.Length - 1) newGlobalScore += ";";
        }
        Debug.Log("save : " + newGlobalScore);
        PlayerPrefs.SetString("Scores", newGlobalScore);
        
    }

    void ShowLvlScore (int lvl, string t, string d, string r )
    {
        labels[lvl - 1].GetComponent<UILabel>().text = "Temps : " + t + "\nMorts : " + d + "\nRatio : " + r;
    }
}
