import System from './System';
import StateMachine from '../StateMahines/StateMachine';
import Stack from '../Database/Stack/Stack';
class StateSystem<T> extends System {
  constructor(name: string) {
    super(name);
    this.m_states = new StateMachine<T>();
    this.m_stateStack = new Stack<T>();
  }

  protected m_states: StateMachine<T>;
  protected m_stateStack: Stack<T>;
  private initStateAction!: (state: StateMachine<T>) => void;

  public initStates(act: (state: StateMachine<T>) => void) {
    this.initStateAction = act;
  }

  public onActived(): void {
    if (this.m_states.StateCount == 0) {
      if (this.initStateAction != null) {
        this.initStateAction(this.m_states);
      }
    }
    this.m_states.start();
  }
  public onDisactived(): void {
    this.m_states.stop();
  }

  public changeState(state: T, beKeepStack: boolean = false): void {
    if (this.m_states.CurrentState == state) return;
    if (beKeepStack) this.m_stateStack.push(this.m_states.CurrentState);
    this.m_states.changeState(state);
  }
  public CurrentState(): T {
    return this.m_states.CurrentState;
  }
  public BackState(): boolean {
    if (this.m_stateStack.Length == 0) return false;
    let lastState = this.popState();
    this.changeState(lastState);
    return true;
  }

  protected popState(): T {
    return this.m_stateStack.pop();
  }
}
export default StateSystem;
