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, 64],
  popupAnchor: [0, -64]
});
var datapoints;
var woBischIcon2 = L.icon({
  iconUrl: '/static/images/marker-all.png',
  iconSize: [64, 64],
  iconAnchor: [32, 32],
  popupAnchor: [0, 0]
});
var bounds;
var boundsSwitzerland = new L.LatLngBounds([[47.826186, 10.511814], [45.797054, 5.925007]]);

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

function vbat2icon(level) {
  switch (level) {
    case 1:
      fa_battery_string = "fa-battery-empty";
      icon_color = "has-text-danger";
      break;
    case 2:
      fa_battery_string = "fa-battery-quarter";
      icon_color = "has-text-warning";
      break;
    case 3:
      fa_battery_string = "fa-battery-half";
      icon_color = "has-text-info";
      break;
    case 4:
      fa_battery_string = "fa-battery-three-quarters";
      icon_color = "has-text-link";
      break;
    case 5:
      fa_battery_string = "fa-battery-full";
      icon_color = "has-text-success";
      break;
    default:
      fa_battery_string = "fa-battery-slash";
      icon_color = "has-text-danger";
  }

  return '<span class="icon ' + icon_color + '"><i class="fas ' + fa_battery_string + '"></i></span>';
}

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

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

    datapoints = mydata['data'];
    $('#datetimeslider').attr('max', datapoints.length - 1);
    $('#datetimeslider').val(datapoints.length - 1);
    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: [20, 20] });
  });
}

$(document).ready(function () {
  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] });
  });


  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);
  map.setView(L.latLng(lat, lon), 10);
  marker = L.marker([lat, lon], { icon: woBischIcon, zIndexOffset: 1000 }).addTo(map);
  $('#reportrange span').html(moment(start).locale('de').format('D. MMM YYYY') + ' - ' + moment(stop).locale('de').format('D. MMM YYYY'));

  refreshDatapoints(deveui, start, stop);
});

$(function () {
  var start = moment({ hour: 0 });
  var end = moment();
  var s_start = start.utc().format('YYYY-MM-DDTHH:mm:ss[Z]');
  var s_end = end.utc().format('YYYY-MM-DDTHH:mm:ss[Z]');

  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_end = end.utc().format('YYYY-MM-DDTHH:mm:ss[Z]');
    refreshDatapoints(deveui, s_start, s_end);
  }

  $('#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);
}
