document.addEventListener('readystatechange', event => {
  // When HTML/DOM elements are ready:
  if (event.target.readyState === "interactive") {
    document.querySelector("table.cols-5").classList.remove("table-striped");
    setTimeout(() => {
      predictEvent();
    }, 500);
  }
}, { passive: true });

async function getNetwork() {
  let obj;
  const res = await fetch('/api/v1/network');
  obj = await res.json();

  return obj;
}

function predictFights(network) {
  let fights = document.querySelectorAll("table.cols-5 tbody .fight");
  fights.forEach((fight) =>  {
    let result = fight.querySelector('.views-field-field-result');
    let resultText = result.textContent.trim();
    let fightIdDiv = fight.querySelector('.views-field-field-fighter-one div');
    let fightId = "";
    if (fightIdDiv) {
      fightId = fightIdDiv.dataset.id;
    }
    if (fightId.length > 0) {
      const fightDataEndpoint = '/api/v1/fight-data/' + fightId;
      fetch(fightDataEndpoint).then(res => res.json()).then(data => {
        obj = data
      })
        .then(() => {
          let predictions = network.run(obj);
          if (predictions.fighter_one > predictions.fighter_two) {
            // Get fighter one name and set as prediction.
            let f1Name = fight.querySelector('.views-field-field-fighter-one').textContent.trim();
            fight.lastElementChild.textContent = f1Name + " (" + Number.parseFloat(predictions.fighter_one * 100).toFixed(4) + " %)";
            if (f1Name == resultText) {
              fight.lastElementChild.classList.add("correct");
            } else {
              fight.lastElementChild.classList.add("incorrect");
            }

          } else {
            // Get fighter two name and set as prediction.
            let f2Name = fight.querySelector('.views-field-field-fighter-two').textContent.trim();
            fight.lastElementChild.textContent = f2Name + " (" + Number.parseFloat(predictions.fighter_two * 100).toFixed(4) + " %)";
            if (f2Name == resultText) {
              fight.lastElementChild.classList.add("correct");
            } else {
              fight.lastElementChild.classList.add("incorrect");
            }
          }
        });
    }
  });

}


function predictEvent() {
  const net = new brain.NeuralNetwork();
  let curNet = getNetwork();
  curNet
    .then(res => {
      net.fromJSON(JSON.parse(res.data));
      predictFights(net);
    })
    .catch(error => {console.log("i got issues")});
}

