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

public class Checkpoint : MonoBehaviour {

	public float					loadTime = 12.0f;
	public float					unloadTime = 4.0f;
	public float					bonusByMinions = 1.0f;
	public GameObject 	position1;
	public GameObject 	position2;
	public GameObject 	position3;
	public GameObject 	position4;
	public GameObject 	position5;
	public GameObject	spriteManager;
	public float 				minionSpeedToPos = 2.0f;
	
	[HideInInspector]
	public bool					isCheckpointEnabled = false;
	
	List<GameObject>		listMinions = new List<GameObject>();
	List<GameObject>		listSlots = new List<GameObject>();
	AltarAnimations			spriteManagerScript;
	DateTime					dateLoadBegin;
	bool								isCharging = true;
	
	void Awake(){
		listSlots.Add(position1);
		listSlots.Add(position2);
		listSlots.Add(position3);
		listSlots.Add(position4);
		listSlots.Add(position5);
		spriteManagerScript = spriteManager.GetComponent<AltarAnimations>();
	}
	
	void Update(){
		if (listMinions.Count > 0)
			MoveMinionsToPos();
		compareTime();
	}
	
	void MoveMinionsToPos(){
		int index = 0;
		foreach (GameObject minion in listMinions){
			if (minion)
				minion.transform.position = Vector3.Lerp(minion.transform.position, listSlots[index].transform.position,  (Time.deltaTime * minionSpeedToPos) / (Vector3.Distance(minion.transform.position, listSlots[index].transform.position) / 1));
			++index;
		}
	}
	
	void compareTime(){
		if (!isCheckpointEnabled && isCharging &&  listMinions.Count > 0 && DateTime.Now >= dateLoadBegin.AddSeconds(loadTime - bonusByMinions * listMinions.Count)){
			spriteManagerScript.Charged();
			isCheckpointEnabled = true;
			GameObject.Find("Main Camera").GetComponent<SoundDispenser>().PlaySound(SoundDispenser.e_music.ALTAR);
			GameObject.Find("Referee").GetComponent<GameDirector>().altarFallen();
		}
		if (isCheckpointEnabled && !isCharging && DateTime.Now >= dateLoadBegin.AddSeconds(unloadTime)){
			spriteManagerScript.NotCharging();
			isCheckpointEnabled = false;
			GameObject.Find("Referee").GetComponent<GameDirector>().altarLost();
		}
	}
	
	public void AddMinion(GameObject newMinion){
		listMinions.Add(newMinion);
		spriteManagerScript.Charging();
		isCharging = true;
		if (listMinions.Count == 1)
			dateLoadBegin = DateTime.Now;
	}
	
	public void RemoveMinion(GameObject minion){
		foreach (GameObject obj in listMinions){
			if (obj == minion){
				listMinions.Remove(obj);
				if (listMinions.Count <= 0 && !isCheckpointEnabled){
					spriteManagerScript.NotCharging();
					isCharging = false;
				}
				else if (listMinions.Count <= 0 && isCheckpointEnabled){
					dateLoadBegin = DateTime.Now;
					isCharging = false;
				}
				return ;
			}
		}
	}
	
	public void KillAllMinions(){
		foreach (GameObject obj in listMinions){
			GameObject.Find("MinionManager").GetComponent<MinionManager>().RemoveMinion(obj);
			Destroy(obj);
		}
		listMinions.Clear();
	}
}