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

//This script courtesy of a tutorial: https://unity3d.com/learn/tutorials/topics/scripting/events-creating-simple-messaging-system

public class EventManager : MonoBehaviour
{
	private Dictionary<string, Vector3Event> vector3EventDictionary;

	private Dictionary<string, UnityEvent> eventDictionary;

	private static EventManager eventManager;

	public static EventManager instance
	{
		get
		{
			if (!eventManager)
			{
				eventManager = FindObjectOfType(typeof(EventManager)) as EventManager;

				if (!eventManager)
				{
					Debug.LogError("There needs to be one active EventManger script on a GameObject in your scene.");
				}
				else
				{
					eventManager.Init();
				}
			}

			return eventManager;
		}
	}

	void Init()
	{
		if (eventDictionary == null)
		{
			eventDictionary = new Dictionary<string, UnityEvent>();
		}

		if (vector3EventDictionary == null)
		{
			vector3EventDictionary = new Dictionary<string, Vector3Event>();
		}
	}

	public static void StartListening(string eventName, UnityAction listener)
	{
		UnityEvent thisEvent = null;
		if (instance.eventDictionary.TryGetValue(eventName, out thisEvent))
		{
			thisEvent.AddListener(listener);
		}

		else
		{
			thisEvent = new UnityEvent();
			thisEvent.AddListener(listener);
			instance.eventDictionary.Add(eventName, thisEvent);
		}
	}

	public static void StartListening(string eventName, UnityAction<Vector3> listener)
	{
		Vector3Event thisEvent = null;
		if (instance.vector3EventDictionary.TryGetValue(eventName, out thisEvent))
		{
			thisEvent.AddListener(listener);
		}

		else
		{
			thisEvent = new Vector3Event();
			thisEvent.AddListener(listener);
			instance.vector3EventDictionary.Add(eventName, thisEvent);
		}
	}

	public static void StopListening(string eventName, UnityAction listener)
	{
		if (eventManager == null)
			return;
		UnityEvent thisEvent = null;
		if (instance.eventDictionary.TryGetValue(eventName, out thisEvent))
		{
			thisEvent.RemoveListener(listener);
		}
	}

	public static void StopListening(string eventName, UnityAction<Vector3> listener)
	{
		if (eventManager == null)
			return;
		Vector3Event thisEvent = null;
		if (instance.vector3EventDictionary.TryGetValue(eventName, out thisEvent))
		{
			thisEvent.RemoveListener(listener);
		}
	}

	public static void TriggerEvent(string eventName)
	{
		UnityEvent thisEvent = null;
		if (instance.eventDictionary.TryGetValue(eventName, out thisEvent))
		{
			thisEvent.Invoke();
		}
	}

	public static void TriggerEvent(string eventName, Vector3 position)
	{
		Vector3Event thisEvent = null;
		if (instance.vector3EventDictionary.TryGetValue(eventName, out thisEvent))
		{
			thisEvent.Invoke(position);
		}
	}
}