var urlParams = new URLSearchParams(window.location.search);
var deveui = urlParams.get('deveui');
var alias = urlParams.get('alias');
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, 64],
  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-text-success 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, zIndexOffset: 500 }).bindPopup(moment(date).format('DD.MM.YYYY HH:mm')));
        lat = i[1];
        lon = i[2];
      }

      if (markers.length > 0) {
        marker = L.marker([lat, lon], { icon: woBischIcon, zIndexOffset: 1000 }).addTo(map);
      }

      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] });
      marker.bindPopup(myhtml).openPopup();
    } else {
      $('#map').hide();
      $('#datetimeslider').hide();
      $('#chart').html(`<article class="message is-danger">
  <div class="message-body">
    Keine GPS-Messpunkte f&uuml;r diese Zeitperiode.<br /><br />Hinweis: heruntergeladene Daten enthalten alle &Uuml;bermittlungen, auch die ohne GPS-Messpunkt (L&auml;ngen- und Breitengrade haben den Wert 0).
  </div>
</article>`);
      $('#chart').show();
    }
  });
}

function SetGreenzonePrecision(gz,i) {
    var coords = gz.split(",",4);
    return parseFloat(coords[0]).toFixed(i)+','+parseFloat(coords[1]).toFixed(i)+','+parseFloat(coords[2]).toFixed(i)+','+parseFloat(coords[3]).toFixed(i);
}

function updateURLParameter(url, param, paramVal){
    var newAdditionalURL = "";
    var tempArray = url.split("?");
    var baseURL = tempArray[0];
    var additionalURL = tempArray[1];
    var temp = "";
    if (additionalURL) {
        tempArray = additionalURL.split("&");
        for (var i=0; i<tempArray.length; i++){
            if(tempArray[i].split('=')[0] != param){
                newAdditionalURL += temp + tempArray[i];
                temp = "&";
            }
        }
    }

    var rows_txt = temp + "" + param + "=" + paramVal;
    return baseURL + "?" + newAdditionalURL + rows_txt;
}

$(document).ready(function () {
  var greenzone = urlParams.get('greenzone');
  if (greenzone == null) {
     greenzone = "";
  }
  $("#modal-yes").click(function () {
    $("#yesnomodal").removeClass("is-active");
    $.ajax({
      url: "save_tracker_greenzone",
      type: "get", //send it through get method
      dataType: "json",
      data: {
        deveui: deveui,
        greenzone: greenzone
      },
      success: function (response) {
        if (response.rc == 0) {
           $('#greenzone_'+$('#deveui').html()).html($('#greenzone').val());
        }
        location.reload();
      },
      error: function (xhr) {
        //Do Something to handle error
      }
    });
  });

  $("#modal-no").click(function () {
    $("#yesnomodal").removeClass("is-active");
  });

  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,
    selectArea: true
  });
  map.setMinZoom(map.getBoundsZoom(map.options.maxBounds));

  map.on('areaselected', (e) => {
    greenzone = SetGreenzonePrecision(e.bounds.toBBoxString(),5); // lon, lat, lon, lat

    // Construct URLSearchParams object instance from current URL querystring.
    var queryParams = new URLSearchParams(window.location.search);
 
    // Set new or modify existing parameter value. 
    queryParams.set("greenzone", greenzone);
 
    // Replace current querystring with the new one.
    history.replaceState(null, null, "?"+queryParams.toString());
    
    $("#yesnomodalbody").html(greenzone);
    $("#yesnomodal").addClass("is-active");
  });

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

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

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

  $( "#datetimeslider" ).bind('mouseup', 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);

  $('#reportrange span').html(moment(s_start).locale('de').format('D. MMM YYYY') + ' - ' + moment(s_stop).locale('de').format('D. MMM YYYY'));

  if (greenzone != "") {
    var coords = greenzone.split(",",4);
    var latlngs = [[coords[1], coords[0]], [coords[3], coords[2]]];
    var rectOptions = {color: 'Green', weight: 1}
    var rectangle = L.rectangle(latlngs, rectOptions);
    rectangle.addTo(map);
  }

  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);
  //console.log("updateSliderTooltip", datapoints[c.value][1], datapoints[c.value][2]);
}
