const dataCenterModel = require("../model/dataCenters");

async function getNearestDataCenter(clientIp) {
  const dataCenters = [
    { name: "USA LA", ip: "192.154.230.77" },
    { name: "UK", ip: "213.171.195.48" },
    // { name: "SG", ip: "131.153.48.50" },
    { name: "GERMEN", ip: "88.198.49.188" },
    { name: "Indin", ip: "1.186.154.0" },
    { name: "SG", ip: "219.75.27.16" },
  ];

  const pingResults = await dataCenterModel.getPingResults(
    dataCenters,
    clientIp
  );

  console.log(clientIp);

  if (Object.keys(pingResults).length > 0) {
    return Object.keys(pingResults).reduce((a, b) =>
      pingResults[a].rtt < pingResults[b].rtt ? a : b
    );
  } else {
    return null;
  }
}

async function getAllPingResults() {
  const dataCenters = [
   { name: "USA LA", ip: "192.154.230.77" },
    { name: "UK", ip: "213.171.195.48" },
    // { name: "SG", ip: "131.153.48.50" },
    { name: "GERMEN", ip: "88.198.49.188" },
    { name: "Indin", ip: "1.186.154.0" },
    { name: "SG", ip: "219.75.27.16" },
  ];

  return dataCenterModel.getPingResults(dataCenters);
}

module.exports = {
  getNearestDataCenter,
  getAllPingResults,
};
