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

class HttpMachine {
  constructor() {
    this.stateMachine = createMachine({
      id: "args",
      initial: "idle",
      predictableActionArguments: true,
      states: {
        idle: {
          on: {
            START: { target: "requesting" },
          },
        },
        requesting: {
          invoke: {
            src: this.request,
            onDone: {
              target: "response",
            },
            onError: {
              target: "error",
              actions: [this.setError],
            },
          },
        },
        response: {
          on: {
            START: { target: "requesting" },
          },
        },
        error: {
          on: {
            START: { target: "requesting" },
          },
        },
      },
    });
    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() {}

  request = (context, event) =>
    new Promise((resolve, reject) => {
      let cmd = event.cmd;
      let options = event.params;
      if(!options){
        return resolve(event);
      }
      const that = this;
      axios(options)
        .then(function (response) {
          let data = response.data;
          that.eventEmitter.emit(cmd, data);
          return resolve(data);
        })
        .catch(function (error) {
          console.log("【error】", error);
          that.send({ type: "ERROR" });
          return reject(error);
        });
    });

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

module.exports.HttpMachine = HttpMachine;
