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

[System.Serializable]
[XmlRoot ("condition")]
public class Condition
{
	[System.Serializable]
	public enum Type
	{
		[XmlEnum("equal")] Equal,
		[XmlEnum("less")]  Less,
		[XmlEnum("great")]  Greater,
		[XmlEnum("eless")] LessOrEqual,
		[XmlEnum("egreat")] GreaterOrEqual,
		[XmlEnum("noneq")] NoneEqual,
		[XmlEnum("or")]    Or, // 0 - false 1 - true
		[XmlEnum("and")]   And,
		[XmlEnum("xor")]   Xor
	}

	[XmlAttribute("a")]
	public string firstArgumentName = "";
	[XmlAttribute("b")]
	public string secondArgumentName = "";
	[XmlAttribute ("con")]
	public Type condition = Type.Equal;

	public Condition() {}
	
	public Condition(string newValueA, Type newCondition, string newValueB)
	{
		condition = newCondition;
		firstArgumentName = newValueA;
		secondArgumentName = newValueB;
	}
	
	public Condition(string trigger, Type newCondition = Type.Greater, int constantValue = 0)
	{
		condition = newCondition;
		firstArgumentName = trigger;
		secondArgumentName = constantValue.ToString();
	}

	public bool Check () {
		if (firstArgumentName == "" || secondArgumentName == "")
		{
			Debug.LogWarning("Condition contain empty value");
		}
		// if argument can be parsed as int - its numeric, else its resource name
		int firstArgumentValue;
		if (!int.TryParse (firstArgumentName, out firstArgumentValue))
		{
			firstArgumentValue = Logic.triggers[firstArgumentName];
		}
		int secondArgumentValue;
		if (!int.TryParse (secondArgumentName, out secondArgumentValue))
		{
			secondArgumentValue = Logic.triggers[secondArgumentName];
		}
		switch (condition)
		{
		default:
		case Type.Equal:
			return firstArgumentValue == secondArgumentValue;
		case Type.NoneEqual:
			return firstArgumentValue != secondArgumentValue;
		case Type.Less:
			return firstArgumentValue < secondArgumentValue;
		case Type.LessOrEqual:
			return firstArgumentValue <= secondArgumentValue;
		case Type.Greater:
			return firstArgumentValue > secondArgumentValue;
		case Type.GreaterOrEqual:
			return firstArgumentValue >= secondArgumentValue;
		case Type.Or:
			return ((firstArgumentValue > 0) || (secondArgumentValue > 0));
		case Type.And:
			return ((firstArgumentValue > 0) && (secondArgumentValue > 0));
		case Type.Xor:
			return ((firstArgumentValue > 0) != (secondArgumentValue > 0));
		}
	}
}   