import { boot } from "quasar/wrappers";
import { io } from "socket.io-client";

const socket = io(process.env.WEBSOCKET_API, {
  transport: ["websocket"],

  path: process.env.WEBSOCKET_PATH,

  auth: {
    apiKey: process.env.WEBSOCKET_API_KEY,
  },

  reconnection: true,
  reconnectionDelay: 1000,
  timeout: 20000,
});

const sendEvent = (room, eventName, data) => {
  const channel = process.env.WEBSOCKET_ROOM + ":" + room + "@" + eventName;

  socket.emit("eventWrapperToNode", {
    channel: channel,
    data: data,
  });
};

const sendEventToLaravel = (eventName, data) => {
  const channel = process.env.WEBSOCKET_ROOM + ":" + eventName;

  socket.emit("eventWrapperToLaravel", {
    channel: channel,
    data: data,
  });
};

const joinRoom = (roomName) => {
  socket.emit("join", process.env.WEBSOCKET_ROOM + ":" + roomName);
};

const leaveRoom = (roomName) => {
  socket.emit("leave", process.env.WEBSOCKET_ROOM + ":" + roomName);
};

export default boot(async () => {
  socket.on("connect", () => {
    console.log("Connected to websocket server!");
  });

  socket.on("disconnect", () => {
    console.log("Disconnected from websocket server!");
  });

  socket.on("connect_error", (error) => {
    console.error("Websocket connection error: ", error);
  });

  socket.on("connect_timeout", (timeout) => {
    console.error("Websocket connection timeout: ", timeout);
  });

  socket.on("reconnect", (attemptNumber) => {
    console.log(
      "Reconnected to websocket server! Attempt number: ",
      attemptNumber,
    );
  });

  socket.on("reconnect_attempt", (attemptNumber) => {
    console.log("Reconnect attempt number: ", attemptNumber);
  });
});

export { socket, joinRoom, leaveRoom, sendEvent, sendEventToLaravel };
