function WebsocketService() {
  let websocket;

  initialize();
  function initialize() {
    let url = "ws://" + location.host + "/ws";
    websocket = new WebSocket(url);
  }

  function onMessage(callback) {
    if (!websocket) throw new Error("Websocket is not open");
    websocket.addEventListener("message", event => {
      callback(event.data);
    });
  }

  function sendMessage(message) {
    if (!isWebsocketOpen()) throw new Error("Websocket is not open");
    websocket.send(message);
  }
  
  function sendJson(jsonObject) {
    let jsonString = JSON.stringify(jsonObject);
    sendMessage(jsonString);
  }

  function isWebsocketOpen() {
    return websocket.readyState === WebSocket.OPEN;
  }

  return {
    onMessage,
    sendJson,
    sendMessage,
  };
}

WebsocketService = new WebsocketService();

export default WebsocketService;
