function load_settings() {
  browser.storage.local.get({auto_close: true})
  .then(
    function(v) {
      document.getElementById('auto-close').checked = v.auto_close === true;
      //console.log('Success', v);
    },
    function() {
      document.getElementById('auto-close').checked = true;
      //console.log('Failure');
    }
  );
}

function save_settings() {
  let v = document.getElementById('auto-close').checked;
  browser.storage.local.set({
    auto_close: v,
  });
  //console.log('stored', v);
}

function trim(word) {
  if (!word) return word;

  var oldword;
  do {
    oldword = word;

    word = word.replace(/^[^a-zA-Z0-9]+/, '');
    word = word.replace(/[^a-zA-Z0-9]+$/, '');
    word = word.replace(/^Bug#/i, '');
    word = word.replace(/^#/, '');
  } while ( oldword != word );

  return word;
}

function open_tab(url) {
  return new Promise((resolve, reject) => {
    browser.tabs.create({url:url, active:false})
      .then(
        function() {
          resolve();
        },
        function(err) {
          //console.log('Error creating tab', err);
          reject(err);
        }
      );
  });
}

function open_link(url, in_new_tab) {
  //console.log('open_link', url, in_new_tab);

  if (in_new_tab) {
    return open_tab(url);
  }

  //console.log('querying active tab');
  return new Promise((resolve, reject) => {
    browser.tabs.query({active:true, currentWindow:true})
      .then(
        function(tabs) {
          //console.log('active tab queried');
          browser.tabs.executeScript(tabs[0].id, {file: '/icedeb-content.js'})
            .then(
              function(){
                //console.log('content script executed');
                browser.tabs.sendMessage( tabs[0].id, {url:url} )
                  .then(
                    function() {
                      //console.log('message sent');
                      resolve();
                    },
                    function(err) {
                      console.log('error sending message', err);
                      reject(err);
                    }
                  );
              },
              function(err){
                console.log('Error executing script. Probably a system tab is active', err, tabs[0]);
                open_tab(url)
                  .then(
                    function() { resolve(); },
                    function(err) { reject(err); } );
              });

        },
        function(err) {
          console.log('Error querying the active tab of the current window', err);
          open_tab(url)
            .then(
              function() { resolve(); },
              function(err) { reject(err) }
            );
        }
      );
  });
}

function link_clicked(e) {
  //console.log(e.target.tagName);
  let autoclose = true;

  if (e.target.tagName == 'A') {
    open_link(e.target.href, e.button == 1)
      .then( function() {
        if (autoclose) {
          //console.log('closing pop-up');
          window.close();
        }
      });
    e.preventDefault();
    return false;
  }

  let clip_input = document.getElementById("clipboard");
  let clip = trim(clip_input.value);

  if(clip_input.value == '') return;

  let url;

  switch (e.target.id) {
    case 'bts':
      url = 'https://bugs.debian.org/' + clip;
      break;
    case 'pts':
      url = 'https://tracker.debian.org/' + clip;
      break;
    case 'deb':
      url = 'https://packages.debian.org/' + clip;
      break;
    case 'ml':
      url = 'https://lists.debian.org/msgid-search/' + clip;
      break;
    case 'ddpo':
      url = 'https://qa.debian.org/developer.php?login=' + clip;
      break;
    case 'dmd':
      url = 'https://udd.debian.org/dmd.cgi?email1=' + clip;
      break;
    case 'buildd':
      url = 'https://buildd.debian.org/' + clip;
      break;
    case 'security':
      clip = clip.replace(' ', '-');
      clip = clip.toUpperCase();
      url = 'https://security-tracker.debian.org/tracker/' + clip;
      break;
    case 'piuparts':
      url = `https://piuparts.debian.org/sid/source/${clip.substring(0,1)}/${clip}.html`;
      break;
    case 'r-b':
      url = 'https://tests.reproducible-builds.org/debian/rb-pkg/' + clip + '.html';
      break;
  }

  open_link(url, e.button == 1)
    .then( function() {
      if (autoclose) {
        //console.log('closing pop-up');
        window.close();
      }
    });

  e.preventDefault();
  return false;
}

function check_likely_inputs(q) {
  let cnt = document.getElementById('button-list-container').classList;

  cnt.remove('like-b', 'like-p', 'like-m', 'like-i', 'like-s');
  document.querySelectorAll('.likely')
    .forEach((el) => {
        el.classList.remove('likely');
    });

  q = q.replace(/^\s+/, '');
  q = q.replace(/\s+$/, '');

  if ( /^#?\d+$/.test(q) || /^CVE-/.test(q) )
    cnt.add('like-b');

  if ( /^[a-z0-9][a-z0-9\-+.]+$/.test(q) )
    cnt.add('like-p');

  if ( /.@[a-z0-9-]/i.test(q) )
    cnt.add('like-m');

  if ( /^<.+@.+>$/.test(q) )
    cnt.add('like-i');

  if ( /^d[sl]a[- ]\d+(-\d+)?$/i.test(q) )
    cnt.add('like-s');

  document.querySelectorAll('.like-b .hint.b, .like-p .hint.p, .like-m .hint.m, .like-i .hint.i, .like-s .hint.s')
    .forEach((el) => {
      el.parentElement.parentElement.classList.add('likely');
    } );
}

function react_to_clipboard_text(text) {
  let clip_input = document.getElementById("clipboard");
  clip_input.value = text;
  clip_input.focus();
  clip_input.setSelectionRange(0, clip_input.value.length);

  check_likely_inputs(text);
}

function get_clipboard_contents() {
  if (navigator.clipboard && navigator.clipboard.readText) {
    navigator.clipboard.readText().then(function(q){
      react_to_clipboard_text(q);
    });
  }
  else {
    let clip_pot = document.getElementById('clip-pot');
    let clip_input = document.getElementById("clipboard");
    clip_pot.focus();
    if (document.execCommand("Paste")) {
      let q = clip_pot.textContent.trim();
      react_to_clipboard_text(q);
    }
  }
}

window.addEventListener('DOMContentLoaded', (e) => {
  document.querySelectorAll('.icedeb-button, #button-list-container a')
    .forEach(function(el){
      el.addEventListener('mouseup', link_clicked);
    });

  document.querySelector('#clipboard')
    .addEventListener('input', function(ev) {
      check_likely_inputs(ev.target.value);
    });

  document.addEventListener('change', (e) => {
    if ( !e.target.classList.contains('icedeb-option') )
      return;

    save_settings();
  });

  window.requestAnimationFrame(()=>{
    window.requestAnimationFrame(get_clipboard_contents);
  });
});

// vim: sw=2
