var apx = apx || {};
apx.tracker = {};
apx.tracker.getinfodevice = async () => {
  const device = {};
  //console.log(navigator);
  device.useragent = navigator.userAgent || navigator.vendor || window.opera;
  device.typedevice = /iPad/i.test(device.useragent) ? "ipad" : "";
  device.typedevice = /iPhone/i.test(device.useragent) ? "iphone" : "";
  device.typedevice = /iPod/i.test(device.useragent) ? "ipod" : "";
  device.typedevice = /Android/i.test(device.useragent) ? "android" : "";
  device.typedevice =
    device.typedevice == "" &&
    /Windows NT|Macintosh|Linux/i.test(device.useragent)
      ? "PC"
      : "";
  console.log(
    "test linux",
    /Windows NT|Macintosh|Linux/i.test(device.useragent)
  );
  device.type =
    device.type === "" && /Mobi/i.test(device.userAgent) ? "mobile" : "";
  device.os = /Windows NT/i.test(device.useragent) ? "windows" : "";
  device.os = /Macintosh/i.test(device.useragent) ? "mac" : "";
  device.os = /Linux/i.test(device.useragent) ? "linux" : "";
  const ipinfo = await axios.get("https://ipinfo.io/json");
  console.log(ipinfo);
  if (
    ipinfo &&
    ipinfo.data &&
    ipinfo.data !== null &&
    typeof ipinfo.data === "object" &&
    Object.keys(ipinfo.data).length > 0
  ) {
    if (ipinfo.data.ip) device.ip = ipinfo.data.ip;
    if (ipinfo.data.city) device.city = ipinfo.data.city;
    if (ipinfo.data.country) device.country = ipinfo.data.country;
  }
  device.screenWidth = window.screen.width;
  device.screenHeight = window.screen.height;
  const connection =
    navigator.connection ||
    navigator.mozConnection ||
    navigator.webkitConnection;
  if (connection) {
    device.connection = `${connection.effectiveType}_${connection.downlink} Mbps`;
  }
  device.lang = navigator.language;
  device.plugins = Array.from(navigator.plugins).map((plugin) => plugin.name);
  //console.log(device)
  return device;
};
apx.tracker.hit = (data) => {
  if (!data.consentcookie && localStorage.getItem("consentcookie"))
    data.consentcookie = localStorage.getItem("consentcookie");
  if (!data.lasttm && localStorage.getItem("lasttm"))
    data.lasttm = localStorage.getItem("lasttm");
  if (!data.xuuid && localStorage.getItem("xuuid"))
    data.xuuid = localStorage.getItem("xuuid");
  if (!data.xapp && localStorage.getItem("xapp"))
    data.xapp = localStorage.getItem("xapp");
  if (apx.data.headers.xalias != "anonymous")
    data.alias = apx.data.headers.xalias;
  let missing = "";
  [("xapp", "srckey", "xuuid", "lasttm", "consentcookie")].forEach((k) => {
    missing += !data[k] ? `${k},` : "";
  });
  if (missing !== "") {
    console.log(`Check your trktag ${missing} are missing`);
    return;
  }
  let urltrack = "/trk/cdn/trkret/empty.json?";
  Object.keys(data).forEach((d) => {
    urltrack += `d=${data[d]}&`;
  });
  urltrack = urltrack.slice(0, -1);
  //console.log(urltrack);
  axios.get(urltrack);
};
apx.tracker.load = () => {
  if (!localStorage.getItem("consentcookie")) {
    document
      .querySelectorAll('div:not([wco-name="tracker"])')
      .forEach((el) => {
        el.classList.add("opacity-40");
        el.style.pointerEvents = "auto";
  });
    document.querySelectorAll("[wco-name='tracker']").forEach((el) => {
      const tpldata = `${apx.data.pagename}_${el.id}_trackerconsentform`;
      if (!apx.data.tpldata[tpldata] || !apx.data.tpldata[tpldata].introtext) {
        console.log(` ${tpldata} does not exist check your file`);
      } else {
        el.innerHTML = Mustache.render(
          apx.data.tpl.trackerconsentform,
          apx.data.tpldata[tpldata]
        );
      }
    });
  } else {
    // test if last loading was <10minutes then send a new tag
    const tm = dayjs().valueOf();
    const lasttmtxt = localStorage.getItem("lasttm");
    const lasttm = lasttmtxt ? Number(lasttmtxt) : null;
    //console.log(lasttm, tm, tm - lasttm > 10 * 60 * 1000);
    if (lasttm && tm - lasttm > 10 * 60 * 1000) {
      localStorage.setItem("lasttm", tm);
      apx.tracker.hit({ srckey: "visitwwws" });
    }
  }
};
apx.tracker.setconsent = async (tagid, choice) => {
  //localStorage.setItem("consentcookie", choice);
  if (!localStorage.getItem("xuuid")) {
    const uuid = ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
      (
        c ^
        (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
      ).toString(16)
    );
    localStorage.setItem("xuuid", uuid);
    apx.data.headers.xuuid = uuid;
    const tm = dayjs().valueOf();
    localStorage.setItem("lasttm", tm);
    apx.save();
  }
  if (["acceptstatisticcookies", "acceptfullcookies"].includes(choice)) {
    const infodevice = await apx.tracker.getinfodevice();
    //console.log(infodevice);
    axios.post(`/api/apxtri/trackings/newdevice`, infodevice, {
      headers: apx.data.headers,
    });
  }
  apx.tracker.hit({ srckey: "firstvisitwwws" });
  document.querySelectorAll('div:not([wco-name="tracker"])').forEach((el) => {
    el.classList.remove("opacity-40");
    el.style.pointerEvents = "auto";
  });
  document.getElementById(tagid).classList.add("hidden");
};

apx.readyafterupdate(apx.tracker.load);
