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

public class MinigameFeedback : MonoBehaviour {

	//Public 
	public GameObject lanceDanceCombo;
	public List<Image> lanceDanceComboImages = new List<Image>();
	public int maxComboDanceAllowed = 8;
	public LanceTween lanceTweenInstance;

	private MinigameManager minigameManager;
	private LanceTween lanceTween;
	private RitualActivationManager ritualActivationInstance;

	private Transform[] childsOfLanceDanceCombo;

	public Sprite[] danceImages;


	[ContextMenu("InitVars")]
	private void InitVar()
	{
		lanceDanceCombo = GameObject.Find ("LanceDanceComboGroup");
	}

	void Awake()
	{
	//	Debug.Log ("AAA", this);
	}

	void Start()
	{
		lanceTweenInstance = LanceTween.instance;
		ritualActivationInstance = RitualActivationManager.instance;

		MinigameManager.instance.OnShowCorrectSequence += HandleCorrectSequence;
		RitualManager.instance.OnEndRitual += HandleEndRitual;

		minigameManager = GetComponent<MinigameManager>();
		lanceTween = GetComponent<LanceTween>();

		//Init and get all the child initially!
		lanceDanceCombo.SetActive(true);
		childsOfLanceDanceCombo = lanceDanceCombo.GetComponentsInChildren<Transform>();
		lanceDanceCombo.SetActive(false);

		//ritualActivationInstance.RefreshRitualButtonsAvailability();

	}
	
	void HandleCorrectSequence(int[] sequence)
	{
		if(sequence.Length <= maxComboDanceAllowed)
		{
			lanceTweenInstance.SwipeOutLanceRituals();

			//Init Combo dance lance bar.
			LanceDanceComboInit(sequence.Length);
			
			for (int i = 0; i < sequence.Length; i++) 
			{
				SetColor (i, sequence [i]);
			}

			//Clear the Images. 
			lanceDanceComboImages.Clear();
		}
		else
		{
			Debug.LogError("You Exceed the max number of combo dance allowed!");
		}

	}

	public void HandleEndRitual()
	{
		lanceTweenInstance.SwipeOutLanceCombo ();
		lanceTweenInstance.SwipeInLanceRituals();
		ritualActivationInstance.RefreshRitualButtonsAvailability();
	}

	public void LanceDanceComboInit(int comboDanceToShow)
	{
		int i = 0;
		foreach (Transform child in childsOfLanceDanceCombo)
		{
			//Skip the father.
			if(i > 0)
			{
				if( i > comboDanceToShow)
				{
					child.gameObject.SetActive(false);
				}
				else
				{
					child.gameObject.SetActive(true);
					lanceDanceComboImages.Add (child.GetComponent<Image>());
				}
			}

			i++;
		}

		Debug.Log ("COUNT " + lanceDanceComboImages.Count);

	}

	public void SetColor(int sequentialIndex, int danceIndex){

		var sr = lanceDanceComboImages [sequentialIndex];

		 //this gameObject is a child, because its transform.parent is not null
		Color col = Color.white;
		switch (danceIndex) {
			case 0:
				col = Color.yellow;
				break;
			case 1:
				col = Color.blue;
				break;
			case 2:
				col = Color.green;
				break;
		}
		col += Color.white * 0.5f;
		col.a = 1;
		// TODO: FIX COLOR   sr.color = col;

		sr.sprite = danceImages[danceIndex];
	}
}
