const invocation = new XMLHttpRequest();
const url = 'https://pad.xpub.nl/p/special_issue_8_cnn/export/txt';

function findCategories(data){
  // Return categories that this page is part of
  // by doing a reversed dictionary lookup
  var current_url = window.location.href;
  var keys = Object.keys(data)
  var categories = [];
  for(var i=0; i<keys.length; i++){
    var urls = data[keys[i]];
    for(var x=0; x<urls.length; x++){
      if(urls[x] === current_url){
        console.log('MATCH:', keys[i]);
        categories.push(keys[i]);
      }
    }
  }
  return categories;
}

function CategoryNetworkNavigator(data){
  // Pick two categories that this page is part of
  // and insert links to other pages of the same category

  var data = JSON.parse(data);

  // Find categories that this page is part of
  var categories = findCategories(data);

  // Select a pseudo-randomised category for buttonA
  var buttonA = categories[Math.floor(Math.random() * categories.length)];
  document.querySelectorAll('#buttonA button')[0].textContent = buttonA;

  // Select another category for buttonB
  var indexA = categories.indexOf(buttonA);
  categories.splice(indexA, 1);
  var buttonB = categories[Math.floor(Math.random() * categories.length)];
  document.querySelectorAll('#buttonB button')[0].textContent = buttonB;

  // Insert a link for each button
  // to another page of the same category
  var linksA = data[buttonA];
  var linksB = data[buttonB];
  linksA.splice(window.location.href, 1);
  linksB.splice(window.location.href, 1);
  document.getElementById("buttonA").href = linksA[Math.floor(Math.random() * linksA.length)];
  document.getElementById("buttonB").href = linksB[Math.floor(Math.random() * linksB.length)];
}

function readEtherpadJSON(){
  if (invocation){
    invocation.open( "GET", url, true );
    invocation.onreadystatechange = function() {
      console.log('ready!');
      if (invocation.readyState === 4 && invocation.status === 200) {
        console.log('invocation:', invocation);
        CategoryNetworkNavigator(invocation.responseText);
      }
    };
    invocation.send();
  }
  return invocation;
}

function insertCNN(cnn_template){
  document.body.innerHTML = cnn_template + document.body.innerHTML;
  readEtherpadJSON();
}

var cnn_template = '<!-- START CNN -->\
  <div id="cnn">\
    <div class="button_container">\
      <a id="buttonA" href="http://b-e-e-t.r-o-o-t.net/pages/please_to_foshan.html"><button class="cnn-button">WHAT IS A NETWORK?</button></a>\
    </div>\
    <div class="button_container">\
      <a id="buttonB" href="http://richfolks.club/"><button class="cnn-button">AUTONOMY AND ITS CONTINGENCIES</button></a>\
    </div>\
    <a id="sitemap" href="https://issue.xpub.nl/08/"><button class="cnn-button">netmap</button></a>\
  </div>\
  <link rel="stylesheet" type="text/css" href="./style2.css">\
  <!-- END CNN -->'

insertCNN(cnn_template);
