const { FileOperationMachine } = require("../../connect/file");
const { ArgsMachine } = require("../../connect/args");
const EventEmitter = require("events");
const { ESMachine } = require("../../connect/esDB");
const { RTCPullMachine } = require("../../connect/rtc");

class ISource {
  constructor(iSource,context) {
    Object.assign(this, iSource,context);
    this.connectStateMachine;
    this.eventEmitter = new EventEmitter();
    this.state = "init";
    this.isStart = false;
  }
  update(iSource) {
    Object.assign(this, iSource);
  }

  mutationUpdate(iSource) {
    console.log("mutationUpdate is Start ? ", this.isStart);
    var flag = this.isStart;
    this.close();
    Object.assign(this, iSource);
    this.open();
    if (flag) {
      this.start();
    }
  }
  open() {
    if (this.connectType == "fileSystem") {
      this.connectStateMachine = new FileOperationMachine();
    } else if (this.connectType == "args") {
      this.connectStateMachine = new ArgsMachine();
    }else if (this.connectType == "esDB") {
      this.connectStateMachine = new ESMachine();
    }else if (this.connectType == "rtc") {
      this.connectStateMachine = new RTCPullMachine(this.config);
    }
    this.state = this.connectStateMachine.stateMachine.initialState.value;
    this.connectStateMachine.onTransition = (state) => {
      this.state = state;
      console.log("state:", state);
    };
  }
  close() {
    this.isStart = false;
    this.connectStateMachine?.eventEmitter.removeAllListeners("close");
    this.connectStateMachine?.eventEmitter.on("close", (data) => {
      this.eventEmitter.emit("close", data);
    });
    this.connectStateMachine?.send({
      type: "CLOSE",
      cmd: "close",
    });
  }

  start(params) {
    this.isStart = true;
    this.connectStateMachine.eventEmitter.removeAllListeners("start");
    this.connectStateMachine.eventEmitter.on("start", (data) => {
      this.eventEmitter.emit("start", data);
    });
    this.connectStateMachine.send({
      type: "START",
      params: params,
      cmd: "start",
    });
  }

  stop() {
    this.isStart = false;
  }

  pause() {}

  resume() {
    this.isStart = true;
  }

  query(params) {
    this.isStart = true;
    this.connectStateMachine.eventEmitter.removeAllListeners("query");
    this.connectStateMachine.eventEmitter.on("query", (data) => {
      this.eventEmitter.emit("query", data);
    });
    this.connectStateMachine.send({
      type: "START",
      params: params,
      cmd: "query",
    });
  }

  getTaskStatus(params) {
    this.connectStateMachine.eventEmitter.removeAllListeners("getTaskStatus");
    this.connectStateMachine.eventEmitter.on("getTaskStatus", (data) => {
      this.eventEmitter.emit("getTaskStatus", data);
    });
    this.connectStateMachine.send({
      type: "START",
      params: params,
      cmd: "getTaskStatus",
    });
  }

  
}

module.exports.ISource = ISource;
