using System.Windows.Media;
using Machinations.FromFlash.graph;

namespace Machinations.FromFlash.machinations.model
{
    /// <summary>
    /// Machinations node, can change resources. much more rare then converter
    /// </summary>
    public class Trader : Source
    {
        private bool m_actAsConverter;

		public Trader()
        {
            m_activationMode = ActivationMode.Passive;
        }

        public override NodeClass NodeClass => NodeClass.Trader;

        public override void Fire() 
		{
			//super.fire();
			for (int i = 0; i < m_inputs.Count; i++)
			{
			    var connection = m_inputs[i] as StateConnection;
			    if (connection != null && connection.Inhibited) return;
			}
            SetFiring();

            Pull();
            LogSelf();
        }

        public override void Prepare(bool doEvents) 
		{
			base.Prepare(doEvents);
    		if (ResourceOutputCount< 2 || ResourceInputCount< 2)
            {
                m_actAsConverter = true;
            } else {
                m_actAsConverter = false;
            }
        }

        public override void ReceiveResource(Color color, ResourceConnection flow) 
		{
			if (m_actAsConverter)
            {
				base.ReceiveResource(color, flow);
			} else
            {
				//redistribute
				for (int i = 0; i < m_outputs.Count; i++) {
					ResourceConnection fl = m_outputs[i] as ResourceConnection;
					if (fl !=null && fl.Color == flow.Color) {
						fl.Resources.Add(new Resource(color, 0));
						break;
					}
				}
				if (CheckInputs()) Satisfy();
				
			}
		}
		
		public override void Satisfy()
		{
			if (m_actAsConverter)
            {
				base.Satisfy();
			} else
            {
                CheckInhibition();
			}
			if (!Inhibited)
            {
				foreach (GraphConnection t in m_outputs)
				{
				    if (t is StateConnection) ((StateConnection)t).Fire();
				}
            }
		}
    }
}
