const { createMachine, interpret } = require("xstate");
const EventEmitter = require("events");
const fs = require("fs");

class ArgsMachine {
  constructor() {
    this.stateMachine = createMachine({
      id: "args",
      initial: "idle",
      predictableActionArguments: true,
      states: {
        idle: {
          on: {
            START: { target: "output" },
          },
        },
        output: {
          invoke: {
            src: this.output,
            onDone: {
              target: "idle",
            },
            onError: {
              target: "error",
              actions: [this.setError],
            },
          },
        },
        error: {
          on: {
            START: { target: "output" },
          },
        },
      },
    });
    this.fsmSevice = interpret(this.stateMachine)
      .onTransition((state) => {
        this.state = state.value;
        this.onTransition(this.state);
      })
      .start();
    this.eventEmitter = new EventEmitter();
  }

  send(event) {
    this.fsmSevice.send(event);
  }
  onTransition() {}

  output = (context, event) =>
    new Promise((resolve, reject) => {
      let cmd = event.cmd;
      this.eventEmitter.emit(cmd, event.params);
      return resolve(event);
    });

  setError = (context, event) =>
    new Promise((resolve, reject) => {
      console.log("setError:", event.data);
      return resolve();
    });
}


module.exports.ArgsMachine = ArgsMachine;
