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

public class ProcessListOfLevels : Process {

    struct FileInformation
    {
        public string Name;
        public string FullName;
    }

    [SerializeField]
    private GameObject scrollviewContent;

    public Text m_text;

    public string levelsPath;
    private GameObject levelButton;

    private Sprite[] spritesArray;
    private Dictionary<string, Sprite> sprites;
    private bool spritesLoaded = false;

    // Use this for initialization
    void Awake ()
    {

        levelsPath = Application.dataPath + "/levels/";

        Debug.Log(levelsPath);

        //m_text.text = levelsPath;

        levelButton = Resources.Load<GameObject>("UIPrefabs/LevelButton");

	}

    public void Start()
    {
        if (!spritesLoaded)
            LoadSprites();

    }

    private void LoadSprites()
    {
        spritesArray = Resources.LoadAll<Sprite>("UI/Interface");
        sprites = new Dictionary<string, Sprite>();

        foreach (Sprite s in spritesArray)
        {
            sprites.Add(s.name, s);
        }

        spritesLoaded = true;
    }

    public override void BeforeActivation()
    {
        base.BeforeActivation();

        for (int i = 0; i < scrollviewContent.transform.childCount; i++)
        {
            Destroy(scrollviewContent.transform.GetChild(i).gameObject);
        }


    }

    public override void AfterActivation()
    {
        base.AfterActivation();


        if (!spritesLoaded)
            LoadSprites();


        StartCoroutine(PreloadLevels());
    }

    private void ReadFromFile(string list)
    { // Read all levels in the defined directory

        string[] listOfLevels = list.Trim().TrimEnd(Environment.NewLine.ToCharArray()).Split('\n');

        Array.Sort(listOfLevels);

        int iterator = 0;

        foreach (string level in listOfLevels)
        {
            //Debug.Log(file.ToString());

            FileInformation file = new FileInformation();
            file.Name = level;
            file.FullName = levelsPath + level;

            Debug.Log(file.Name);

            string buttonImageOrientation = "";
            if (iterator % 3 == 0)
            {
                buttonImageOrientation = "Left";
            }
            else if (iterator % 3 == 1)
                buttonImageOrientation = "Face";
            else if (iterator % 3 == 2)
                buttonImageOrientation = "Right";

            GameObject b = Instantiate(levelButton);

            Button[] childButtons = b.GetComponentsInChildren<Button>();

            foreach (Button cb in childButtons)
            {
                if (cb.gameObject.name == "LevelName")
                {
                    string buttonName = "Button" + UnityEngine.Random.Range(1, 4);
                    cb.GetComponent<Image>().sprite = sprites[buttonName];
                    cb.gameObject.GetComponentInChildren<Text>().text = file.Name.Substring(0, file.Name.LastIndexOf("."));
                }
                else if (cb.gameObject.name == "LevelScore")
                {
                    int score = (PlayerPrefs.HasKey(file.Name)) ? PlayerPrefs.GetInt(file.Name) : 0;
                    cb.GetComponent<Image>().sprite = sprites[score + "Star" + buttonImageOrientation];
                }
                cb.GetComponent<Button>().onClick.RemoveAllListeners();
                FileInformation f = file;
                cb.GetComponent<Button>().onClick.AddListener(() => onButtonClick(f));
            }



            b.transform.SetParent(scrollviewContent.transform);

            iterator++;

        }
    }

    IEnumerator PreloadLevels()
    {

        WWW www;

        if (!Application.isWebPlayer)
            www = new WWW("file://" + levelsPath + "list.info");
        else
            www = new WWW(levelsPath + "list.info");


        yield return www;

        ReadFromFile(www.text);
    }

    private void onButtonClick(FileInformation file)
    {
        StateMachine.instance.UpdateState(StateMachine.STATE.LOADING);
        LevelReader.instance.currentLevelName = file.Name;
        //Debug.Log(LevelReader.instance.currentLevelName);

        Debug.Log(file.FullName);

        
        if(!Application.isWebPlayer)
            LevelReader.instance.SelectLevel("file://" + file.FullName);
        else
            LevelReader.instance.SelectLevel(file.FullName);

        SoundDispenser.instance.clickOnButton.Play();
    }

    public void onBackButtonClick()
    {
        StateMachine.instance.UpdateState(StateMachine.STATE.MENU);
        SoundDispenser.instance.clickOnButton.Play();
    }

    public void onResetButtonClick()
    {
        StateMachine.instance.UpdateState(StateMachine.STATE.RESET);
        SoundDispenser.instance.clickOnButton.Play();
    }



}
