import user from '~/store/user';
const CLIENT_NAME = `${user.user_id}|${user.user_realname}`;
export function createSocket(options, hooks) {
  const ws = new WebSocket("wss://socket.bozedu.net");
  ws.addEventListener('message', (e) => {
    if (e.data) {
      try {
        const data = JSON.parse(e.data);
        if (CLIENT_NAME === data.from_client_name)
          return;
        if (!['ping', 'login'].includes(data.type)) {
          console.groupCollapsed(`Socket : ${data.type}`);
          console.log(data);
          console.groupEnd();
        }
        if (data.type === 'login') {
        }
        if (data.type === 'say') {
          const content = Object.assign(Object.assign({}, data), { content: JSON.parse(decodeURIComponent(data.content)) });
          console.groupCollapsed(`├─ Socket Say:`);
          console.log(content);
          console.groupEnd();
          hooks.message(content);
        }
      }
      catch (error) {
        console.error(error);
      }
    }
  });
  ws.addEventListener('error', (err) => {
    console.error('ws error :>> ', ws, err);
  });
  ws.addEventListener('open', (e) => {
    ws.send(JSON.stringify({
      "type": "login",
      "client_name": CLIENT_NAME,
      "room_id": `${options.room}`
    }));
  });
  return ws;
}
export function socketSend(ws, content) {
  ws.send(JSON.stringify({
    type: "say",
    to_client_id: 'all',
    content: encodeURIComponent(JSON.stringify(content))
  }));
}
