using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
public class LevelsManager : MonoBehaviour {
	[System.Serializable]
	public class Level
	{
		public string LevelText;
		public int UnLoked;
		public bool IsInteractable;

	//	public Button.ButtonClickedEvent OnClickEvent;
	}

	public GameObject button;
	public Transform Spacer;
	public List<Level> LevelList;

	// Use this for initialization
	void Start () {
		//DeleteAll ();
		FillList ();
	}
	void FillList(){
		foreach (var level in LevelList) {
			GameObject newbutton = Instantiate (button) as GameObject;
			LevelButton _button = newbutton.GetComponent<LevelButton> ();
			_button.LevelText.text = level.LevelText;
			//Level
			if(PlayerPrefs.GetInt ("Level"+ _button.LevelText.text)==1){
				level.UnLoked = 1;
				level.IsInteractable = true;
			}
			_button.UnLocked = level.UnLoked;
			_button.GetComponent<Button> ().interactable = level.IsInteractable;
			_button.GetComponent<Button>().onClick.AddListener(() => LoadLevels("Level"+_button.LevelText.text)); 

			//Stars
			if (PlayerPrefs.GetInt ("Level" + _button.LevelText.text + "_stars") == 1) {
				_button.Star1.SetActive (true);
				_button.Star2.SetActive (false);
				_button.Star3.SetActive (false);
			}

			if (PlayerPrefs.GetInt ("Level" + _button.LevelText.text + "_stars") == 2) {
				_button.Star1.SetActive (true);
				_button.Star2.SetActive (true);
				_button.Star3.SetActive (false);
			}
			if (PlayerPrefs.GetInt ("Level" + _button.LevelText.text + "_stars") ==3 ) {
				_button.Star1.SetActive (true);
				_button.Star2.SetActive (true);
				_button.Star3.SetActive (true);
			}

			newbutton.transform.SetParent (Spacer);
			//escalar
			newbutton.transform.localScale = new Vector3(1,1,1);
		}
		SaveAll ();
	}

	void SaveAll(){


//		if (PlayerPrefs.HasKey ("Level1"))
//		{
//			return;
//		}
//		else
		{
			

			GameObject[] allButtons = GameObject.FindGameObjectsWithTag ("LevelButton");
			foreach (GameObject buttons in allButtons)
			{
				LevelButton button = buttons.GetComponent<LevelButton> ();
				PlayerPrefs.SetInt("Level" + button.LevelText.text, button.UnLocked);
			}
		}
	}


	void DeleteAll(){
		PlayerPrefs.DeleteAll ();
	}


	void LoadLevels(string value){
		SceneManager.LoadScene (value);
		//Application.LoadLevel (value);
	}
	public void menuatras(){
		SceneManager.LoadScene ("Menu");
	}
}
