const axios = require("axios");
const shared = require("./shared.js");
const { Log } = require("./logs.js");
let hostIDs = [];
var monitorInterval;

async function Monitoring() {
  await initHostList();
  Log(`\n[${shared.now()}] Inizio monitoring`);
  //monitora tutti gli host della lista
  shared.eventEmitter.on("tokenRenewalStart", () => {
    clearInterval(monitorInterval);
  });
  shared.eventEmitter.on("tokenRenewalEnd", () => {
    monitorInterval = setInterval(Request, minute - 1);
  });
  monitorInterval = setInterval(Request, minute - 1);
}

async function Request() {
  var hosts = [];
  for (const element of hostIDs) {
    var obj = {
      id: element,
      [element]: await isConnected(element),
    };
    hosts.push(obj);
  }
  shared.setHosts(hosts);
}

async function isConnected(hostID) {
  try {
    const response = await axios.get(
      `https://api.netbird.io/api/peers/${hostID}`,
      {
        headers: {
          Accept: "application/json",
          Authorization: `Token ${shared.getToken()}`,
        },
      }
    );
    Log(`[${shared.now()}] ${hostID} connected: ${response.data.connected}`);
    return response.data.connected;
  }
  catch (error) {
    Log(`[${shared.now()}] ${error}`);
    process.exit(3);
    }
}

async function initHostList() {
  if ("HOSTNAMES" in process.env) {
    let envHostnames = process.env.HOSTNAMES;

    if (
      envHostnames !== null &&
      envHostnames !== undefined &&
      envHostnames !== ""
    ) {
      if (envHostnames.includes(";")) {
        envHostnames = envHostnames.split(";");

        for (const host of envHostnames) {
          try {
            const response = await axios.get(
              `https://api.netbird.io/api/peers?name=${host}`,
              {
                headers: {
                  Accept: "application/json",
                  Authorization: `Token ${shared.getToken()}`,
                },
              }
            );
            response.data.forEach((host) => {
              hostIDs.push(host.id);
            });
          } catch (error) {
            Log(
              `[${shared.now()}] Errore nella verifica e aggiunta al monitoraggio di un host: ${error}`
            );
            process.exit(3);
          }
        }
      } else {
        try {
          const response = await axios.get(
            `https://api.netbird.io/api/peers?name=${envHostnames}`,
            {
              headers: {
                Accept: "application/json",
                Authorization: `Token ${shared.getToken()}`,
              },
            }
          );
          hostIDs.push(response.data[0].id);
        } catch (error) {
          Log(
            `[${shared.now()}] Errore nella verifica e aggiunta al monitoraggio di un host: ${error}`
          );
          process.exit(3);
        }
      }
    }
  } else if ("HOSTIDS" in process.env) {
    let envHostIDs = process.env.HOSTIDS;

    if (envHostIDs !== null && envHostIDs !== undefined && envHostIDs !== "") {
      if (envHostIDs.includes(";")) {
        envHostIDs = envHostIDs.split(";");

        for (const host of envHostIDs) {
          try {
            const response = await axios.get(
              `https://api.netbird.io/api/peers/${host}`,
              {
                headers: {
                  Accept: "application/json",
                  Authorization: `Token ${shared.getToken()}`,
                },
              }
            );
            hostIDs.push(response.data.id);
          } catch (error) {
            Log(
              `[${shared.now()}] Errore nella verifica e aggiunta al monitoraggio di un host: ${error}`
            );
            process.exit(3);
          }
        }
      } else {
        try {
          const response = await axios.get(
            `https://api.netbird.io/api/peers/${envHostIDs}`,
            {
              headers: {
                Accept: "application/json",
                Authorization: `Token ${shared.getToken()}`,
              },
            }
          );
          hostIDs.push(response.data.id);
        } catch (error) {
          Log(
            `[${shared.now()}] Errore nella verifica e aggiunta al monitoraggio di un host: ${error}`
          );
          process.exit(3);
        }
      }
    }
  } else {
    Log(
      `[${shared.now()}] Nessun peer specificato, verranno monitorati tutti i peer disponibili`
    );
    try {
      const response = await axios.get(`https://api.netbird.io/api/peers`, {
        headers: {
          Accept: "application/json",
          Authorization: `Token ${shared.getToken()}`,
        },
      });
      response.data.forEach((element) => {
        hostIDs.push(element.id);
      });
    } catch (error) {
      Log(`[${shared.now()}] ${error}`);
      process.exit(3);
    }
  }

  Log(`[${shared.now()}] ID rilevati:`);
  hostIDs.forEach((element) => {
    Log(`[${shared.now()}] ${element}`);
  });
}

module.exports = { Monitoring };
