using System;
using Unity.IO.LowLevel.Unsafe;
using UnityEngine;

namespace AI.Base {
  abstract public class StateManager : MonoBehaviour {
    protected IState CurrentState;

    virtual protected void Update() {
      CurrentState?.Tick();
      IState next = GetNextState();
      if (next != null && next != CurrentState) {
        CurrentState.Stop();
        CurrentState = next;
        CurrentState.Start();
      }
    }

    abstract protected IState GetNextState();
  }

  public class StateNode : ScriptableObject, IState {
    protected Transform Owner;

    virtual public void Initialize(Transform ownerTransform) {
      Owner = ownerTransform;
    }

    virtual public StateNode InitializeCopy(Transform ownerTransform) {
      Owner = ownerTransform;
      return ScriptableObject.CreateInstance(this.GetType()) as StateNode;
    }

    virtual public void Start() {}
    virtual public void Stop() {}
    virtual public void Tick() {}

    virtual public IState GetNextState() => this;
  }
}
