import Vue from "vue";
// import store from "@/store";

export let wsNotify = new WebSocket(
  `ws://${window.location.hostname}:3000/ws/v1/notify`
);

window.wsNotify = wsNotify;

wsNotify.eventBus = new Vue();

wsNotify.eventBus.$on("reconnect", () => {
  wsNotify = new WebSocket(
    `ws://${window.location.hostname}:3000/ws/v1/notify`
  );
});

// let timer = null;

wsNotify.onopen = function (event) {
  console.log("websocket is conneted!", event);
  wsNotify.eventBus.$emit("open", event);
  // timer = setInterval(function() {
  //   wsNotify.send(JSON.stringify({ type: 'heartbeat', ts: Date.now(), token: store.getters.token }))
  // }, 1000)
};

wsNotify.onmessage = function (event) {
  const message = JSON.parse(event.data);
  wsNotify.eventBus.$emit("message", message);
};

wsNotify.onerror = function (error) {
  console.log(error);
  wsNotify.eventBus.$emit("error", error);
  // if (timer) clearInterval(timer);
};

wsNotify.onclose = function (event) {
  console.log("websocket is colosed!", event);
  wsNotify.eventBus.$emit("close", event);
  // if (timer) clearInterval(timer);
};