using UnityEngine;
using System.Linq;
using System.Collections;

public class MinigameManager : MonoBehaviour {

	public int[] currentCorrectSequence;

	public static MinigameManager instance;

	private float timerSeconds = 0f;
	private bool timerOn = false;

	public int maxMinigameSeconds = 10;

	public delegate void ShowCorrectSequenceAction(int[] sequence);
	public event ShowCorrectSequenceAction OnShowCorrectSequence;

	public float CurrentTimer{
		get{
//			Debug.Log (timerSeconds);
			return (maxMinigameSeconds-this.timerSeconds );
		}
	}

	void Awake(){
		instance = this;
	}

	public void SendFakeSequence(){
		var list = new int[0];
		if (OnShowCorrectSequence != null)
			OnShowCorrectSequence (list);
	}

	public void SpawnSequence(int length){

		var seq = new int[length];
		for (int i = 0; i < length; i++) {
			seq [i] = Random.Range (0, Adept.MAX_DANCES);
		}
		currentCorrectSequence = seq;

		StartTimer ();

		if (OnShowCorrectSequence != null)
			OnShowCorrectSequence (seq);
	}

	public void CheckCorrectAdepts(){

		// Sequence correctness should be checked on checkpoints sorted by game id
		Adept[] adepts = GetSortedAdepts();

		//for(int i=0; i < adepts.Length; i++){
		//	Debug.Log(adepts[i].targetCheckpoint.id);
		//}

		// Check Sequence
		int correctSeqFirstElem = currentCorrectSequence[0];
		bool sequenceCorrect = false;
		for(int i = 0; i < adepts.Length; i++){
			if(adepts[i].currentDanceIndex == correctSeqFirstElem){
				// Matching sequence
				bool checkOk = true;
				int currAdeptIndex = i;
				for(int j = 0; j < currentCorrectSequence.Length; j++){
					if(adepts[currAdeptIndex].currentDanceIndex != currentCorrectSequence[j]){
						checkOk = false;
						break;
					}
					currAdeptIndex++;
					if(currAdeptIndex >= adepts.Length){
						currAdeptIndex = 0;
					}
				}
				if(checkOk){
					sequenceCorrect = true;
					break;
				}
			}
		}

		if (sequenceCorrect) {
			RitualManager.instance.CompleteRitual_Dance ();
		}

	}

	public Adept[] GetSortedAdepts()
	{
		Adept[] adepts = FindObjectsOfType<Adept> ();
		Adept holder;

		for(int i = 0; i < adepts.Length; i++)
		{
			int j = i;
			while(j > 0 && adepts.Length > 1)
			{
				if(adepts[j-1].targetCheckpoint.id > adepts[j].targetCheckpoint.id)
				{
					holder = adepts[j-1];
					adepts[j-1] = adepts[j];
					adepts[j] = holder;
					j--;

				}
				else
					break;
			}
		}
		return adepts;
	}

	public void StartTimer(){
		Invoke ("StartTimerDelayed", 2f);
	}

	void StartTimerDelayed(){
		timerSeconds = 0;
		timerOn = true;
	}

	public void StopTimer(){
		timerOn = false;
	}

	void Update(){
		if (timerOn) {
			timerSeconds += Time.deltaTime;

			if (timerSeconds >= maxMinigameSeconds) {
				RitualManager.instance.CompleteRitual_TimeOut ();
				StopTimer ();
			}
		}
	}
}
