import { LogLevels } from "../logLevel.js";
import { fetchRetry } from "./fetch-retry.js";
import { logRocket } from "./logrocket.js";
const http = (url) => {
  const logs = [];
  return {
    log: async (msg, logLevel) => {
      if (logLevel === LogLevels.ERROR || logLevel === LogLevels.FATAL)
        logRocket.error(msg);
      const sendLogs = async (logMsg) => {
        if (window && window.navigator && navigator.sendBeacon) {
          try {
            return navigator.sendBeacon(url, JSON.stringify(logMsg));
          } catch (err) {
            console.error(err);
            return true;
          }
        }
        return fetchRetry({
          url,
          options: {
            method: "POST",
            headers: {
              "Content-Type": "text/plain"
            },
            keepalive: true,
            body: JSON.stringify(logMsg)
          },
          retries: 3
        }).catch(console.error);
      };
      if (logLevel !== LogLevels.ERROR && logLevel !== LogLevels.WARN && logLevel !== LogLevels.FATAL) {
        if (logs.length === 0) {
          window.addEventListener("beforeunload", () => {
            sendLogs(logs).catch(console.error);
          });
          window.addEventListener("unload", () => {
            sendLogs(logs).catch(console.error);
          });
          const handle = setInterval(() => {
            clearInterval(handle);
            if (logs.length === 0) return;
            sendLogs(logs).catch(console.error);
            logs.length = 0;
          }, 1e4);
        }
        logs.push(msg);
      } else {
        await sendLogs(msg);
      }
      return true;
    }
  };
};
export {
  http
};
