using System.Collections.Generic;

namespace WS
{
    ///<summary>状态</summary>
    public abstract class FSMState : WSComponent
    {
        /// <summary>状态Id</summary>
        public abstract int StateId { get; set; }
        /// <summary>触发条件的列表</summary>
        protected List<FSMTrigger> Triggers = new List<FSMTrigger>();
        ///<summary>
        ///Key:TriggerId 
        ///Value:StateId 
        ///条件->输出状态的映射关系
        ///</summary>
        protected Dictionary<int, int> _AllMapping = new Dictionary<int, int>();

        /// <summary>添加条件</summary>
        /// <typeparam name="T">条件类型</typeparam>
        /// <param name="stateid">状态Id</param>
        public void AddTrigger<T>(int stateid) where T : FSMTrigger
        {
            FSMTrigger trigger = ComponentFactory.CreateWithParent<T>(this);
            if (!_AllMapping.ContainsKey(trigger.TriggerId))
            {
                Triggers.Add(trigger);
                _AllMapping[trigger.TriggerId] = stateid;
            }
            else
            {
                trigger.Dispose();
                Log.LogError($"条件 {typeof(T).Name} 已经添加");
            }
        }

        /// <summary>删除条件</summary>
        /// <param name="triggerid">条件Id</param>
        public void DeleteTrigger(int triggerid)
        {
            if (_AllMapping.ContainsKey(triggerid))
            {
                _AllMapping.Remove(triggerid);
                Triggers.RemoveAll(p => p.TriggerId == triggerid);
            }
        }

        /// <summary>查找状态</summary>
        /// <param name="triggerid">条件Id</param>
        /// <returns>状态Id 如果返回值是-1，未找到该状态</returns>
        public int GetOutPutState(int triggerid)
        {
            if (_AllMapping.ContainsKey(triggerid))
                return _AllMapping[triggerid];
            return -1;
        }

        ///<summary>0.初始化状态</summary>
        public abstract void Awake();

        /// <summary>1.进入状态时</summary>
        public abstract void EnterState(FSM fsm);

        /// <summary>2.离开状态时</summary>
        public abstract void ExitState(FSM fsm);

        /// <summary>3.持续状态时，执行的主要行为</summary>
        public abstract void StayState(FSM fsm);

        /// <summary>4.检查转换条件</summary>
        public virtual void Reason(FSM fsm)
        {
            for (int i = 0; i < Triggers.Count; i++)
            {
                if (Triggers[i].HandleEvaluate(fsm))
                {
                    fsm.TriggerSwitchState(Triggers[i].TriggerId);
                }
            }
        }

        public override void Dispose()
        {
            base.Dispose();
            for (int i = 0; i < Triggers.Count; i++)
            {
                Triggers[i].Dispose();
            }
            Triggers.Clear();
            _AllMapping.Clear();
        }
    }
}