var loadReportTable = function (droneId) {
  let reportWrapper = document.getElementById('report-wrapper');
  let slug = document.getElementById('report-slug').innerText;
  let start = document.querySelector('div#daterange>input[name="start"]').value;
  let end = document.querySelector('div#daterange>input[name="end"]').value;

  let uri = '/report/' + slug;
  if (start != '' && end != '') {
    uri += '/daterange/' + start + '/' + end;
  }

  if (droneId !== undefined) {
    uri = '/drone/'+droneId+uri;
  }

  uri = '/api'+uri;

  const grid = new gridjs.Grid({
    columns: [
      'PID',
      'Cron',
      'Status',
      'Runcount',
      'Duration',
      'Timestamp',
      'Created'
    ],
    server: {
      url: uri,
      then: data => data.data.map(row => [
        row.hive_pid,
        row.cron_name,
        gridjs.html(
          '<span class="status ' + row.status + (row.status_info ? ' info' : '') + '" '
            + "data-info='" + JSON.stringify(row.status_info) + "'>"
            + row.status
            + (row.status_info ? ' <span class="material-icons-outlined">open_in_new</span>' : '')
            + '</span>'
        ),
        row.hive_runcount,
        row.hive_duration,
        row.hive_timestamp,
        row.created_at
      ]),
      total: data => data.total
    },
    pagination: {
      limit: 20,
      server: {
        url: (prev, page, limit) => `${prev}?page=${page}&limit=${limit}`
      }
    },
    sort: true,   // TODO Switch to different table renderer? This one has problems with server-side sort...
    footer: {
      'background-color': '#29b474',
      'color': 'white',
      'float': 'left'
    }
  }).render(reportWrapper);

}

/******************************************************************************
 * What to do when the DOM loads...
 ******************************************************************************/

document.addEventListener("DOMContentLoaded", function() {

  // Init drone ID if applicable
  let droneId;
  if (!!document.getElementById('view-node')) {
    droneId = document.getElementById('view-node').value;
    if (!droneId) {
      droneId = undefined;
    }
  }
  console.log('droneId:', droneId);

  // Init daterange inputs
  const pickerElt = document.getElementById('daterange');
  const rangepicker = new DateRangePicker(pickerElt, {
    format: 'yyyy-mm-dd'
  });

  // Init report reload button
  document.addEventListener('click', function(e) {
    if (e.target.id !== 'report-reload') return;
    e.preventDefault();

    let slug = document.getElementById('report-slug').innerText;
    let start = document.querySelector('div#daterange>input[name="start"]').value;
    let end = document.querySelector('div#daterange>input[name="end"]').value;

    let uri = '/report/' + slug;
    if (start != '' && end != '') {
      uri += '/daterange/' + start + '/' + end;
    }
    window.location = uri;
  });

  // OK load the report from API
  loadReportTable(droneId);

  // Init status info modal
  document.addEventListener('click', function(e) {
    if (!e.target.matches('.status') && !e.target.parentNode.matches('.status')) return;
    e.preventDefault();
    let target = (e.target.matches('.status')) ? e.target : e.target.parentNode;

    let modal = document.getElementById('info-modal');
    let close = modal.getElementsByClassName('close')[0];

    close.onclick = function() {
      modal.style.display = "none";
    }

    window.onclick = function(event) {
      if (event.target == modal) {
        modal.style.display = "none";
      }
    }

    // Replace status info in the modal and display it
    let div = document.createElement('div');
    div.innerHTML = '<pre><code data-language="json">'
      + JSON.stringify(JSON.parse(target.dataset.info), null, 2)
      + '</code></pre>';

    Rainbow.color(div, function() {
      let wrapper = document.getElementById('info-wrapper');
      wrapper.innerHTML = '';
      wrapper.appendChild(div);
    });

    modal.style.display = "block";
  });

  // What to do when the view-node selector changes?
  document.addEventListener('input', function(e) {
    if (e.target.id !== 'view-node') return;
    e.preventDefault();

    let droneId = document.getElementById('view-node').value;
    if (!droneId) {
      droneId = undefined;
    }

    let slug = document.getElementById('report-slug').innerText;
    let start = document.querySelector('div#daterange>input[name="start"]').value;
    let end = document.querySelector('div#daterange>input[name="end"]').value;

    let uri = '/report/' + slug;
    if (start != '' && end != '') {
      uri += '/daterange/' + start + '/' + end;
    }

    if (droneId !== undefined) {
      uri = '/drone/'+droneId+uri;
    }

    console.log('Navigating to:', uri);
    window.location = uri;
  });

});
