var urlParams = new URLSearchParams(window.location.search);
var deveui = urlParams.get('deveui');
var alias = urlParams.get('alias');
var lon = urlParams.get('lon');
var lat = urlParams.get('lat');
var map;
var lcontrol;
var last_slider_position;
var markers = [];
var marker;
var allmarkers = L.layerGroup();
var woBischIcon = L.icon({
  iconUrl: '/static/images/marker.png',
  iconSize: [64, 64],
  iconAnchor: [32, 32],
  popupAnchor: [0, -64]
});
var datapoints;
var woBischIcon2 = L.icon({
  iconUrl: '/static/images/marker-all.png',
  iconSize: [64, 64],
  iconAnchor: [32, 32],
  popupAnchor: [0, -64]
});
var bounds;
var boundsSwitzerland = new L.LatLngBounds([[47.826186, 10.511814], [45.797054, 5.925007]]);

var dstart = moment({ hour: 0 });
var s_start = dstart.utc().format('YYYY-MM-DDTHH:mm:ss[Z]');
var dstop = moment();
var s_stop = dstop.utc().format('YYYY-MM-DDTHH:mm:ss[Z]');

function vbat2icon(percent) {
  if (percent <= 20) {
     fa_battery_string = "fa-battery-empty";
     icon_color = "has-background-danger-dark has-text-white pl-2 pr-2";
  } else if (percent <= 40) {
     fa_battery_string = "fa-battery-quarter";
     icon_color = "has-background-danger-light has-text-danger pl-2 pr-2";
  } else if (percent <= 60) {
     fa_battery_string = "fa-battery-half";
     icon_color = "has-text-success pl-2 pr-2";
  } else if (percent <= 80) {
     fa_battery_string = "fa-battery-three-quarters";
     icon_color = "has-text-success pl-2 pr-2";
  } else {
     fa_battery_string = "fa-battery-full";
     icon_color = "has-text-success pl-2 pr-2";
  }

  return '<span class="' + icon_color + '"><i class="fas ' + fa_battery_string + '"></i>&nbsp;' + percent + ' &percnt;</span>';
}

function getDownloadFilename(deveui, start, stop) {
  var mdstart = moment(start);
  var mdstop = moment(stop);
  filename = deveui + "_" + mdstart.format('DD.MM.YYYY') + "_bis_" + mdstop.format('DD.MM.YYYY') + ".csv";
  return filename;
}

function refreshDatapoints(deveui, start, stop) {
  range = ""
  range = range + "&start=" + start;
  range = range + "&stop=" + stop;

  $.getJSON('metrics?deveui=' + deveui + range, function (mydata) {
    if ("msg" in mydata) {
      $('#map').hide();
      $('#datetimeslider').hide();
      if (mydata.msg.includes("expired")) {
        $('#chart').html(`<article class="message is-danger">
  <div class="message-body">
    Abo ist abgelaufen
  </div>
</article>`);
        $('#chart').show();
      } else if (mydata.msg.includes("error:")) {
        $('#map').hide();
        $('#datetimeslider').hide();
        $('#chart').html(`<article class="message is-danger">
  <div class="message-body">
    Fehler im Aufruf
  </div>
</article>`);
        $('#chart').show();
      } else {
        location.reload(true);
      }
      return;
    }

    datapoints = mydata['data'];
    if (datapoints.length > 0) {
      $('#chart').hide();
      $('#map').show();
      $('#datetimeslider').attr('max', datapoints.length - 1);
      $('#datetimeslider').val(datapoints.length - 1);
      $('#datetimeslider').show();
      last_slider_position = datapoints.length - 1;
      var unix_timestamp = datapoints[datapoints.length - 1][0];
      var date = new Date(unix_timestamp * 1000);

      var myhtml = '<p class="has-text-centered"><b>' + alias + '</b><br />' + moment(date).format('DD.MM.YYYY HH:mm') + '<br />' + vbat2icon(datapoints[datapoints.length - 1][4]) + '</p>';
      marker.bindPopup(myhtml).openPopup();

      if (allmarkers !== undefined) {
        map.removeLayer(allmarkers);
      }

      markers = [];

      // we create the layer group with all positions
      for (let i of datapoints) {
        unix_timestamp = i[0];
        date = new Date(unix_timestamp * 1000);
        markers.push(L.marker([i[1], i[2]], { icon: woBischIcon2 }).bindPopup(moment(date).format('DD.MM.YYYY HH:mm')));
      }
      allmarkers = L.layerGroup(markers);
      if (lcontrol != undefined) {
        //lcontrol.clearLayers();
        lcontrol.remove();
      }
      lcontrol = L.control.layers({}).addTo(map);
      lcontrol.addOverlay(allmarkers, 'alle Positionen anzeigen');
      bounds = new L.LatLngBounds([[mydata['max_lat'], mydata['max_lon']], [mydata['min_lat'], mydata['min_lon']]]);
      map.fitBounds(bounds, { padding: [15, 15] });
    } else {
      $('#map').hide();
      $('#datetimeslider').hide();
      $('#chart').html(`<article class="message is-danger">
  <div class="message-body">
    Keine Messpunkte f&uuml;r diese Zeitperiode
  </div>
</article>`);
      $('#chart').show();
    }
  });
}

$(document).ready(function () {
  params = "deveui=" + deveui + "&alias=" + alias + "&start=" + s_start + "&stop=" + s_stop;
  $("#btn_download").attr("href", "/downloadmetrics?" + params);
  $("#btn_download").attr("download", getDownloadFilename(deveui, s_start, s_stop));
  map = new L.Map('map', {
    crs: L.CRS.EPSG3857,
    zoomControl: true,
    maxBounds: boundsSwitzerland,
    doubleClickZoom: false
  });
  map.setMinZoom(map.getBoundsZoom(map.options.maxBounds));

  map.on('dblclick', function (e) {
    map.fitBounds(bounds, { padding: [20, 20] });
  });

  $( "#datetimeslider" ).mousemove(function( event ) {
    updateSliderTooltip(this);
  });

  $( "#datetimeslider" ).bind('touchmove', function( event ) {
    updateSliderTooltip(this);
  });

  var url = 'https://wmts20.geo.admin.ch/1.0.0/ch.swisstopo.pixelkarte-farbe/default/current/3857/{z}/{x}/{y}.jpeg';
  var tilelayer = new L.tileLayer(url);
  map.attributionControl.setPrefix('Source: Swiss Federal Office of Topography')
  map.addLayer(tilelayer);
  marker = L.marker([lat, lon], { icon: woBischIcon, zIndexOffset: 1000 }).addTo(map);
  $('#reportrange span').html(moment(s_start).locale('de').format('D. MMM YYYY') + ' - ' + moment(s_stop).locale('de').format('D. MMM YYYY'));

  refreshDatapoints(deveui, s_start, s_stop);
});

$(function () {
  var start = moment({ hour: 0 });
  var end = moment();

  function cb(start, end) {
    $('#reportrange span').html(start.locale('de').format('D. MMM YYYY') + ' - ' + end.locale('de').format('D. MMM YYYY'));
    s_start = start.utc().format('YYYY-MM-DDTHH:mm:ss[Z]');
    s_stop = end.utc().format('YYYY-MM-DDTHH:mm:ss[Z]');
    params = "deveui=" + deveui + "&alias=" + alias + "&start=" + s_start + "&stop=" + s_stop;
    $("#btn_download").attr("href", "/downloadmetrics?" + params);
    $("#btn_download").attr("download", getDownloadFilename(deveui, s_start, s_stop));
    refreshDatapoints(deveui, s_start, s_stop);
  }

  $('#reportrange').daterangepicker({
    startDate: start.local(),
    endDate: end.local(),
    regional: ["de"],
    "locale": {
      format: 'DD.MM.YYYY',
      "separator": " - ",
      "applyLabel": "Anwenden",
      "cancelLabel": "Abbrechen",
      "fromLabel": "Von",
      "toLabel": "Bis",
      customRangeLabel: 'Benutzerdefiniert',
      "weekLabel": "W",
      "daysOfWeek": [
        "So",
        "Mo",
        "Di",
        "Mi",
        "Do",
        "Fr",
        "Sa"
      ],
      "monthNames": [
        "Jan",
        "Feb",
        "M&auml;r",
        "Apr",
        "Mai",
        "Jun",
        "Jul",
        "Aug",
        "Sep",
        "Okt",
        "Nov",
        "Dez"
      ],
      "firstDay": 1
    },
    ranges: {
      'Heute': [moment(), moment()],
      'Gestern': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
      'Letzte 7 Tage': [moment().subtract(6, 'days'), moment()],
      'Letzte 30 Tage': [moment().subtract(29, 'days'), moment()],
      'Diesen Monat': [moment().startOf('month'), moment().endOf('month')],
      'Letzten Monat': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
    }
  }, cb);

});

function updateSliderTooltip(c) {
  if (datapoints == undefined || datapoints.length == 0) {
    return
  }
  if (c.value == last_slider_position) {
    // we don't do anything if slider position did not change...
    return
  }

  last_slider_position = c.value;
  var unix_timestamp = datapoints[c.value][0];
  var date = new Date(unix_timestamp * 1000);
  var myhtml = '<p class="has-text-centered"><b>' + alias + '</b><br />' + moment(date).format('DD.MM.YYYY HH:mm') + '<br />' + vbat2icon(datapoints[c.value][4]) + '</p>';
  marker.bindPopup(myhtml).openPopup();

  var lat = datapoints[c.value][1];
  var lng = datapoints[c.value][2];
  var newLatLng = new L.LatLng(lat, lng);
  marker.setLatLng(newLatLng);
}
