const WebSocket = require("ws");

const getInstance = function () {
  let wss = globalThis.wss;
  if (wss) {
    // console.log(wss);
    return wss;
  }

  wss = globalThis.wss = new WebSocket.Server({ port: 23333 });
  wss.on("connection", function connection(ws) {
    ws.on("message", function incoming(data) {
      if (typeof data == "string") {
        const dataJson = JSON.parse(data);
        if (dataJson.type == "token") {
          globalThis.__token__ = dataJson.data;
        }
      }
      //   wss.clients.forEach(function each(client) {
      //     if (client.readyState === WebSocket.OPEN) {
      //       client.send(data);
      //     }
      //   });
    });
  });
  return wss;
};

module.exports = getInstance();
