using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Xml.Serialization;

/// <summary>
/// Triggers stock. Main module with resources list 
/// </summary>


public class Logic
{
	[System.Serializable]
	public class Trigger
	{
		[System.Serializable]
		public enum Type
		{
			[XmlEnum("t")]
			trigger,
			[XmlEnum("r")]
			resource,
			[XmlEnum("i")]
			item,
			[XmlEnum("q")]
			quest
		}
		[XmlAttribute("v")]
		public int value = 0;
		[XmlAttribute("n")]
		public string name = "";
		[XmlAttribute("t")]
		public Type type = Type.trigger;
		public Trigger(string triggerName, int triggerValue = 0, Type triggerType = Type.trigger)
		{
			name = triggerName;
			value = triggerValue;
			type = triggerType;
		}
		public Trigger() {}
	}
	public static Logic triggers = new Logic ();
	public Dictionary<string, Trigger> triggerList = new Dictionary<string, Trigger> ();

	public delegate void OnSomeResourcesCountChange();
	public delegate void OnResourceCountChange(int newCount);

	Dictionary<string, OnResourceCountChange> subscriptions = new Dictionary<string, OnResourceCountChange>();
	OnSomeResourcesCountChange allSubscription = () => {}; // default empty delegete - no null check needs

	public int this [string triggerName] {
		get {
			if (triggerList.ContainsKey (triggerName)) {
				return triggerList [triggerName].value;
			}
			return 0;
		}
		set {
			if (!triggerList.ContainsKey (triggerName)) {
				triggerList.Add (triggerName, new Trigger(triggerName, value));
				OnTriggerChanging(triggerName, value);
			} else {
				if (triggerList[triggerName].value != value)
				{
					triggerList[triggerName].value = value;
					OnTriggerChanging(triggerName, value);
				}
			}
		}
	}

	void OnTriggerChanging(string triggerName, int newValue)
	{
		if (subscriptions.ContainsKey (triggerName))
		{
			if (subscriptions[triggerName] != null)
			{
				subscriptions[triggerName](newValue);
			}
			else
			{
				subscriptions.Remove(triggerName);
			}
		}
		allSubscription ();
	}

	public static void Subscribe(string resourceName, OnResourceCountChange onChangeDelegate)
	{
		if (triggers != null && onChangeDelegate != null)
		{
			if (!triggers.subscriptions.ContainsKey (resourceName))
			{
				triggers.subscriptions.Add(resourceName, onChangeDelegate);
			}
			else
			{
				triggers.subscriptions[resourceName] += onChangeDelegate;
			}
			onChangeDelegate(triggers[resourceName]);
		}
	}
	public static void Subscribe(OnSomeResourcesCountChange onChangeDelegate)
	{
		if (triggers != null && onChangeDelegate != null) {
			triggers.allSubscription += onChangeDelegate;
		}
	}
}
