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

/// <summary>
/// 每帧只处于一个状态的处理分发
/// </summary>
public class WidgetStateDispacher  {

    
    Dictionary<int, WidgetStateProcessor> m_StateProcessorDict = new Dictionary<int, WidgetStateProcessor>();
    public Dictionary<int, WidgetStateProcessor> processorDict { get { return m_StateProcessorDict; } }

    int preState = -1;

    public void AddStateProcessor(int stateId, WidgetStateProcessor widgetStateProcessor)
    {
        if (!m_StateProcessorDict.ContainsKey(stateId))
            m_StateProcessorDict.Add(stateId, widgetStateProcessor);
    }


    public void StateProcess<T>(T widget, int stateId) where T: ViewEntity
    {
        if (!m_StateProcessorDict.ContainsKey(stateId))
        {
            //GameDebug.LogError("not ContainsKey:"+ stateId);
            return;
        }
        
        WidgetStateProcessor action = m_StateProcessorDict[stateId];
            
        if (stateId != preState)
        {
            try
            { //与前一个State不同
                m_StateProcessorDict[stateId].OnEnter(widget);
            }
            catch { }
        }

        try
        {
            m_StateProcessorDict[stateId].ActionProcess(widget);
        }
        catch { }

        if (stateId != preState)
        {
            if (m_StateProcessorDict.ContainsKey(preState))
            {
                try
                {
                    m_StateProcessorDict[preState].OnExit(widget);
                }
                catch { }
            }
        }

        preState = stateId;
    }
    

}

public abstract class WidgetStateProcessor
{

    /// <summary>
    /// 首次进入State
    /// </summary>
    /// <param name="widget"></param>
    public virtual void OnEnter<T>(T widget) where T : ViewEntity
    {

    }

    /// <summary>
    /// State中
    /// </summary>
    /// <param name="widget"></param>
    public abstract void ActionProcess<T>(T widget) where T : ViewEntity;

    /// <summary>
    /// 退出State
    /// </summary>
    /// <param name="widget"></param>
    public virtual void OnExit<T>(T widget) where T : ViewEntity
    {

    }
}
