using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


/// <summary>
/// 每帧可能有多个State进行， 处理分发
/// </summary>
public class WidgetMultiStateDispacher<T> where T: class
{
    ViewEntity m_Widget;

    Dictionary<Type, MultiStateProcessor> buffActionDict;

    public WidgetMultiStateDispacher(ViewEntity widget)
    {
        m_Widget = widget;
    }

    public void AddProcessor(Type eneityType, MultiStateProcessor processor)
    {
        if (buffActionDict == null)
            buffActionDict = new Dictionary<Type, MultiStateProcessor>();

        if (!buffActionDict.ContainsKey(eneityType))
            buffActionDict.Add(eneityType, processor);
    }
    
    List<T> preBuffs = new List<T>();
    public void Process(List<T> actions)
    {
        foreach (var buff in actions)
        {
            Type typeId = buff.GetType();

            if (!buffActionDict.ContainsKey(typeId))
            {
               // GameDebug.LogError("not ContainsKey:" + typeId);
                continue;
            }
            var exist = preBuffs.Find(e => e.GetType() == typeId);
            if (exist == null)
            {
                buffActionDict[typeId].OnEnter(m_Widget, buff);
            }
            else
            {
                preBuffs.Remove(exist);
            }

            buffActionDict[typeId].BuffProcess(m_Widget, buff);
        }

        foreach (var expiredBuff in preBuffs)
        {
            Type preTypeId = expiredBuff.GetType();
            if (buffActionDict.ContainsKey(preTypeId))
            {
                buffActionDict[preTypeId].OnExit(m_Widget, expiredBuff);
            }
        }

        if (preBuffs.Count > 0 || actions.Count > 0)
        {
            preBuffs.Clear();
            preBuffs.AddRange(actions);
        }
    }
}
public abstract class MultiStateProcessor
{
    public virtual void OnEnter<T1,T2>(T1 widget, T2 dataCoreEntity)
    {

    }
    public abstract void BuffProcess<T1,T2>(T1 widget, T2 dataCoreEntity);

    public virtual void OnExit<T1,T2>(T1 widget, T2 dataCoreEntity)
    {

    }

}