using System.Collections.Generic;
using UnityEngine;

public class StateMachine
{
    FiniteState state;
    MonoBehaviour subject;
    Stack<FiniteState> pushdown = new Stack<FiniteState>();

    public StateMachine(MonoBehaviour subject)
    {
        UnityEngine.Assertions.Assert.IsNotNull(subject, "subject is null");
        this.subject = subject;
    }
    public void SwitchTo<T>() where T : FiniteState, new()
    {
        //退出状态
        if (state != null)
            state.Exit();
        //分配新状态
        FiniteState newState = new T();
        //状态入栈
        if (newState.isBackEnable)
            pushdown.Push(state);
        else
            pushdown.Clear();
        //初始化新状态
        state = newState;
        state.subject = subject;
        state.Init();
    }
    public void Back()
    {
        UnityEngine.Assertions.Assert.IsNotNull(state, subject.name + " state is null");
        if (state.isBackEnable)
        {
            state.Exit();
            state = pushdown.Pop();
            Debug.Log(state);
        }
        else
            Debug.Log("不要在处于不能返回的状态中调用Back");
    }
    public void Update()
    {
        if (state != null)
            state.Update();
    }
}
