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

public class Key : MonoBehaviour {

	static private int collectedKeyCount = 0;
	static public  void CollectKey() {
		collectedKeyCount++;
		if (targetKeyCountListeners.Count > 0) {
			List<int> keysToDelete = new List<int>();
			foreach (KeyValuePair<int,List<Action>> element in targetKeyCountListeners) {
				Debug.Log("Checking for " + element.Key + " keys against collectedKeyCount=" + collectedKeyCount);
				if (collectedKeyCount >= element.Key) {
					keysToDelete.Add(element.Key);
					int listenerCount = element.Value.Count;
//					Debug.Log("Key count #" + element.Key + " has " + listenerCount + " listeners");
					for (int i = 0; i < listenerCount; i++) {
						element.Value[i](); //Invokes the callback
					}
				}
			}
			
			foreach(int key in keysToDelete) {
				targetKeyCountListeners.Remove(key);
			}
		}
	}
	
	static private Dictionary<int,List<Action>> targetKeyCountListeners;
	
	static public  void ListenToTargetCount(int targetCount, Action callback) {
		if (targetKeyCountListeners.Count > 0 && targetKeyCountListeners.ContainsKey(targetCount)) {
			if (!targetKeyCountListeners[targetCount].Contains(callback)) targetKeyCountListeners[targetCount].Add(callback);
		}
		else {
			targetKeyCountListeners.Add(targetCount, new List<Action>());
			targetKeyCountListeners[targetCount].Add(callback);
		}
	}
	
	static public void ResetCollectedKeys() {
		collectedKeyCount  = 0;
		targetKeyCountListeners = new Dictionary<int, List<Action>>();
	}
	
	
	private void Awake() {
		targetKeyCountListeners = new Dictionary<int, List<Action>>();
	}
	
	private void OnLevelWasLoaded() {
		ResetCollectedKeys();
	}
	
	private void OnTriggerEnter(Collider collider) {
		if (collider.name.StartsWith("Player")) {
			CollectKey();
			KeyPickupEffect.Summon(transform.position);
			GameObject.Destroy(this.gameObject);
		}
	}
}
