import test from "ava";
import FSM from "../../client/fsm.js";

const add_test = () => {
  console.log("Additional function call on state transition passed.");
}

class TestMachine {
  constructor(data) {
    console.log("DATA IS", data);
    this.data = data;
  }

  async open(state, inc) {
    switch(state) {
      case "START":
        console.log("THIS", this);
        this.data.count = this.data.count + inc;
        return "OPEN";
      default:
        return "ERROR";
    }
  }

  close(state, inc) {
    switch(state) {
      case "OPEN":
        this.data.count = this.data.count + inc;
        return ["CLOSED", add_test];
      default:
        return "ERROR";
    }
  }
}

test("Basic FSM operations", async (t) => {
  let data = {count: 0};
  let events = new TestMachine(data);
  let fsm1 = new FSM(data, events);

  fsm1.onTransition((fsm) => {
    console.log("On transition: ", fsm.state);
  });

  await fsm1.do('open', 3);
  t.is(fsm1.state, "OPEN");
  t.is(data.count, 3);

  await fsm1.do('close', 4);
  t.is(fsm1.state, "CLOSED");
  t.is(data.count, 7);

  // test the errors
  await fsm1.do('open');
  t.is(fsm1.state, "ERROR");
  t.is(data.count, 7); // still 2 after error

  t.pass();
});
