using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XNode;
using RPGCreationKit.BehaviourTree;

namespace RPGCreationKit.BehaviourTree
{
    [CreateNodeMenu("RPGCK_BehaviourTree/Reset Below", order = 1)]
    [System.Serializable]
    public class ResetBelowNode : BTNode
    {
        protected override void Init()
        {
            base.Init();
        }

        // Return the correct value of an output port when requested
        public override object GetValue(NodePort port)
        {
            return null; // Replace this
        }


        public int sortbyindex(BTNode a, BTNode b)
        {
            return a.indexInSequence.CompareTo(b.indexInSequence);
        }

        public override NodeState Execute()
        {
            if (m_NodeState == NodeState.Success || m_NodeState == NodeState.Failure)
                if (hasEvaluated == true)
                    return m_NodeState;

            if (!STARTED)
                OnStart();

            List<NodePort> endPorts = GetInputPort("input").GetConnection(0).node.GetOutputPort("outputs").GetConnections();

            List<BTNode> nodes = new List<BTNode>();

            for (int i = 0; i < endPorts.Count; i++)
                nodes.Add((endPorts[i].node as BTNode));

            nodes.Sort(sortbyindex);

            for (int i = indexInSequence+1; i < nodes.Count; i++)
            {
                //Debug.Log("Resetting: " + ((nodes[i]) as BTNode) + " | " + ((nodes[i]) as BTNode).name); 
                ((nodes[i]) as BTNode).m_NodeState = NodeState.Failure;
                ((nodes[i]) as BTNode).hasEvaluated = true;
                ((nodes[i]) as BTNode).ReEvaluate();
            }


            m_NodeState = NodeState.Success;
            hasEvaluated = true;
            return m_NodeState;
        }

        public override void ReEvaluate()
        {
            if (m_NodeState != NodeState.Running)
                base.ReEvaluate();
        }


        public override void OnRemoveConnection(NodePort port)
        {
            base.OnRemoveConnection(port);
            indexInSequence = -1;
        }

        public override void OnStart()
        {
            STARTED = true;
        }
    }
}