

function etherpadChange(tabs) {
  
  const url = document.getElementById('new_pad').value;
  console.log(url);

  browser.tabs.sendMessage(tabs[0].id, {
    command: "etherpadchange",
    url: url,
  });
}

function listenForClicks() {
  document.addEventListener("click", (e) => {

    if (e.target.tagName !== "BUTTON" || !e.target.closest("#popup-content")) {
      // Ignore when click is not on a button within <div id="popup-content">.
      return;
    }
    else {
      browser.tabs
        .query({ active: true, currentWindow: true })
        .then(etherpadChange)
        .catch(err => console.error(err));
    }
  })
}

let etherpad = 'https://pad.constantvzw.org/p/declarations-scratch';
browser.storage.local.get('etherpad').then(function(result){
  if(result.etherpad){
    etherpad = result.etherpad;
  }
}).then(function(){
    let current_pad = document.getElementById('current_pad');
    let new_pad = document.getElementById('new_pad');
    current_pad.innerHTML = etherpad;
    current_pad.href =  etherpad;
    new_pad.value = etherpad;
});

browser.tabs
  .executeScript({file: "../main.js"})
  .then(listenForClicks)
  .catch(err => console.error(err));
