using ftt.Core.Managing;
using UI;
using UnityEngine;

namespace ftt.Gameplay.AI
{
    public class MinotaurBTHandler
    {
        MinotaurEntity entity;
        MinotaurNodeData nodeData;

        BehaviourTree entryBT;
        BehaviourTree patrolBehaviour;
        BehaviourTree chaseBehaviour;

        public MinotaurBTHandler(MinotaurEntity entity, MinotaurNodeData nodeData)
        {
            this.entity = entity;
            this.nodeData = nodeData;

            CreateBehaviourTree(ref entryBT);
        }

        void CreateBehaviourTree(ref BehaviourTree entryBT)
        {
            #region PATROL
            IdleOnArrival idleOnArrival = new IdleOnArrival(nodeData);
            PatrolCheckDistance patrolCheckDistance = new PatrolCheckDistance(nodeData, idleOnArrival);

            PatrolNavigateTo patrolNavigateTo = new PatrolNavigateTo(nodeData);
            PatrolNavToActivator navToActivator = new PatrolNavToActivator(nodeData, patrolNavigateTo);
            PatrolNode patrolNode = new PatrolNode(nodeData, patrolCheckDistance, navToActivator);

            //Create the patrol BT
            patrolBehaviour = new BehaviourTree(patrolNode, nodeData);
            #endregion

            #region CHASE_ATTACK
            //Player looses here
            CatchPlayerAction attackTargetAction = new CatchPlayerAction(nodeData, TheeMou);
            NavToTarget navToTarget = new NavToTarget(nodeData);

            ChaseAttackSelector chaseTarget = new ChaseAttackSelector(nodeData, navToTarget, attackTargetAction);
            //Wait for one second, play the scream sound and animation THEN move to the chase node
            ChaseTargetActivator chaseActivator = new ChaseTargetActivator(nodeData, chaseTarget);

            //Create the chase BT
            chaseBehaviour = new BehaviourTree(chaseActivator, nodeData);
            #endregion

            #region MAIN_BT
            //Create the node activator
            IdlePatrolChaseActivator idlePatrolActivator = new IdlePatrolChaseActivator(nodeData, patrolBehaviour, chaseBehaviour);

            CheckForDetection checkForDetection = new CheckForDetection(nodeData, entity.SetTargetFound);

            INode[] parallerNodes = new INode[]
            {
                checkForDetection,
                idlePatrolActivator
            };

            ParallelExecutor parallelExecutor = new ParallelExecutor(nodeData, parallerNodes);

            entryBT = new BehaviourTree(parallelExecutor, nodeData);
            #endregion
        }

        void TheeMou()
        {
            UIManager.S.EnablePanel("Defeat");

            GameObject.Destroy(entity.gameObject);
        }

        public void UpdateBehaviour()
        {
            if (entryBT != null)
            {
                entryBT.Run();
            }
        }
    }
}