using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XNode;
using RPGCreationKit.BehaviourTree;
using RPGCreationKit.AI;
using System.Reflection;
using RPGCreationKit.BehaviourTree.Data;

namespace RPGCreationKit.BehaviourTree
{
    /// <summary>
    /// Allows the Invoking of a method with the attribute [BT_AIInvokable] from a BehaviourTree
    /// </summary>
    [CreateNodeMenu("RPGCK_BehaviourTree/Actions/AI/AI_Invoke", order = 1)]
    [System.Serializable]
    public class AI_InvokeNode : BTNode
    {

        RckAI thisAI;

        public string MethodToCall;
        public ConditionParameter[] parameters = new ConditionParameter[5];
        public bool solvedRef = false;

        // Use this for initialization
        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 override NodeState Execute()
        {
            if (m_NodeState == NodeState.Success || m_NodeState == NodeState.Failure)
                if (hasEvaluated == true)
                    return m_NodeState;

            if (!STARTED)
                OnStart();

            m_NodeState = NodeState.Running;

            NodesHelper.AIInvokeCall(MethodToCall, thisAI, parameters);

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

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

        public void SolveEventualBTVariablesParameters()
        {
            for (int i = 0; i < parameters.Length; i++)
                if (parameters[i].btVariableValue != null)
                {
                    if (parameters[i].btVariableValue is BT_Float)
                        parameters[i].btVariableValue = (BT_Float)BTReference.SolveReference(this.graph as RPGCK_BT, parameters[i].btVariableValue.name);
                }

            solvedRef = true;
        }

        public override void OnStart()
        {
            thisAI = (this.graph as RPGCK_BT).ai;

            if (!solvedRef)
                SolveEventualBTVariablesParameters();

            STARTED = true;
        }


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