import { Composite, NodeStatus } from "../index";
import { btclass } from "../../core/decorator";

@btclass("Sequence")
export default class Sequence extends Composite {
  onStart(): void {
    super.onStart();
    this.index = 0;
  }

  canExecute(): boolean {
    return this.index < this.children.length && this.status !== NodeStatus.Failure;
  }

  onChildExecuted(status: NodeStatus, _: number): void {
    switch (status) {
      case NodeStatus.Success:
        this.index++;
        if (this.index >= this.children.length) {
          this.status = NodeStatus.Success;
        } else {
          this.status = NodeStatus.Running;
        }
        break;
      case NodeStatus.Failure:
        this.status = NodeStatus.Failure;
        break;
      case NodeStatus.Running:
        this.status = NodeStatus.Running;
        break;
      default:
        break;
    }
  }

  onConditionalAbort(index: number) {
    this.index = index;
    this.status = NodeStatus.Inactive;
  }
}
