using Machinations.FromFlash.graph;

namespace Machinations.FromFlash.machinations.model
{
    /// <summary>
    /// Machinations node, able of consuming resources
    /// </summary>
    public class Drain : MachinationsNode
    {
        public Drain()
        {
            m_activationMode = ActivationMode.Passive;
        }


        public override NodeClass NodeClass => NodeClass.Drain;

        public override void Fire() 
		{
            m_inputs.ForEach(input =>
            {
                if(input is StateConnection && (input as StateConnection).Inhibited) return;
            });
            base.Fire();
            Pull();
        }

        public override void Satisfy() 
		{
			if (!m_inhibited)
            {
                m_outputs.ForEach(output =>
                {
                    if (output is StateConnection) (output as StateConnection).Fire();
                });
			}
			base.Satisfy();
		}
		
		public override void CheckInhibition() 
		{
			bool inhibited = m_inhibited;
			m_inhibited = false;
            m_inputs.ForEach(input =>
            {
                if (input is ResourceConnection) (input as ResourceConnection).CheckInhibition(false);
            });
			m_inhibited = inhibited;
			base.CheckInhibition();
		}
		
		public bool CanDrain()
		{
		    bool forReturn = true;
			m_inputs.ForEach(input =>
			{
			    StateConnection stateConnection = input as StateConnection;
			    if (!(stateConnection.Start is Delay) && !(stateConnection.Start is Gate) &&
			        stateConnection.Label.Type != LabelType.Trigger && stateConnection.Label.Type != LabelType.Trigger &&
			        stateConnection.Label.CheckCondition(stateConnection.State))
			    {
			        forReturn = false;
			    }
			}); 
			return forReturn;
		}
		
		public override string ToMMString()
        {
			return GetMMWhen() + " " + GetMMAct() + " " + GetMMHow() + " drain " + GetMMName();
        }

        protected override void InhibitedChangeForReal()
        {
            base.InhibitedChangeForReal();
            m_inputs.ForEach(input =>
            {
                if (input is ResourceConnection) (input as ResourceConnection).CheckInhibition(false);
            });
        }
    }
}
