const { createMachine, interpret } = require("xstate");
const EventEmitter = require("events");
const { RtcWorker } = require("../work/rtcWorker");

class RTCMsgMachine {
  constructor(config) {
    this.config = config;
    this.stateMachine = createMachine({
      id: "RTCPull",
      initial: "disconnected",
      predictableActionArguments: true,
      states: {
        disconnected: {
          on: {
            START: { target: "connecting" },
          },
        },
        connecting: {
          invoke: {
            src: this.subMsg,
            onDone: {
              target: "connected",
            },
            onError: {
              target: "error",
              actions: [this.setError],
            },
          },
        },
        connected: {
          on: {
            CLOSE: { target: "disconnected", actions: [this.close] },
          },
        },
        error: {
          on: {
            START: { target: "connecting" },
          },
        },
      },
    });
    this.fsmSevice = interpret(this.stateMachine)
      .onTransition((state) => {
        this.state = state.value;
        this.onTransition(this.state);
      })
      .start();
    this.cmd = "start";
    this.eventEmitter = new EventEmitter();
    this.worker = new RtcWorker();
    this.worker.on("roomStatus", (data) => {
      this.eventEmitter.emit(this.cmd, data);
    });
  }

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

  close = (context, event) =>
    new Promise((resolve, reject) => {
      this.worker.close();
    });

  subMsg = (context, event) =>
    new Promise((resolve, reject) => {
      console.log("openRtc:", event);
      this.cmd = event.cmd;
      var roomId = this.config.roomId;
      var params = {
        "roomId": roomId,
      }
      this.worker.subMsg(params);
      this.eventEmitter.emit(this.cmd, "success");
      return resolve();
    });

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

module.exports.RTCMsgMachine = RTCMsgMachine;
