var chart;

function drawGraph(deveui, alias, property, start, stop, minmax, create_graph) {
  range = ""
  range = range + "&start=" + start;
  range = range + "&stop=" + stop;

  var label;
  var labels = {};
  var annotations = {};
  var forceNiceScale = true;
  $(".button").removeClass("is-success");
  if (property=="t") {
    $("#btn_t").addClass("is-success");
    label = 'Temperatur';
    mysubtitle = 'Temperatur in °C';
    minfunc = function(min) { if (min > 0) { return 0 } else { return min } }
    maxfunc = function(max) { return max + 5 }
    labels = {
      offsetX: 35,
      offsetY: -5,
      align: 'right'
    };
  } else if (property=="vp") {
    $("#btn_vp").addClass("is-success");
    label = 'Akkuladung';
    mysubtitle = 'Akkuladung in Prozent';
    minfunc = function(min) { return 0 }
    maxfunc = function(max) { return 100 }
    labels = {
      offsetX: 30,
      offsetY: -5,
      align: 'right'
    };
    forceNiceScale = false;
  } else if (property=="w") {
    $("#btn_w").addClass("is-success");
    label = 'Gewicht';
    mysubtitle = 'Gewicht in Kilogramm';
    minfunc = function(min) { if (min > 5000) { return min  - 2000 } else { return 0 } }
    maxfunc = function(max) { return max + 2000 }
    annotations = {    yaxis: [
          {
            y: minmax.split(",")[0],
            y2: minmax.split(",")[1],
            borderColor: '#000',
            fillColor: '#00FF00'
          }
        ]
      };
    labels = {
      offsetX: 10,
      offsetY: -5,
      align: 'right',
      formatter: function(val, index) {
        return (val / 1000.0).toFixed(3);
      }
    };
  } else if (property==="h") {
    $("#btn_h").addClass("is-success");
    label = 'Luftfeuchtigkeit';
    mysubtitle = 'Luftfeuchtigkeit in Prozent';
    minfunc = function(min) { return 0 } 
    maxfunc = function(max) { return 100 }
    labels = {
      offsetX: 30,
      offsetY: -5,
      align: 'right'
    };
    forceNiceScale = false;
  } else if (property=="p") {
    $("#btn_p").addClass("is-success");
    label = 'Luftdruck';
    mysubtitle = 'Luftdruck in Hektopascal';
    minfunc = function(min) { return 900 } 
    maxfunc = function(max) { return 1060 }
    labels = {
      offsetX: 35,
      offsetY: -5,
      align: 'right'
    };
  } else {
    label = 'Unknown';
    mysubtitle = 'Unknown';
  }
  
  $.getJSON('/metrics?deveui=' + deveui + '&alias=' + alias + '&property=' + property + 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;
    }
    calculated_height = $('.container').height() - $('.navbar').height() - $('#myselectors').height();
    var options = {
      chart: {
        type: 'line',
        height: calculated_height + 'px',
        animations: {
          enabled: false
        }
      },
      stroke: {
        curve: 'smooth'
      },
      title: {
        text: urlParams.get('alias'),
        align: 'center',
        offsetY: 20,
        style: {
          fontSize: '32px'
        }
      },
      subtitle: {
        text: mysubtitle,
        align: 'center',
        offsetY: 60,
        style: {
          fontSize: '12px'
        }
      },
      xaxis: {
        type: "datetime",
        labels: {
          rotate: 0,
          datetimeUTC: false
        }
      },
      yaxis: {
        min: minfunc,
        max: maxfunc,
        forceNiceScale: forceNiceScale,
        labels: labels,
        opposite: true,
        floating: true
      },
      tooltip: {
        x: {
          format: 'dd.MM.yyyy HH:mm'
        }
      },
      annotations: annotations,
      series: [{
        name: label,
        data: mydata
      }]
    }
  
    if (create_graph) {
      chart = new ApexCharts(document.querySelector("#chart"), options);
    } else {
      chart.destroy();
      chart = new ApexCharts(document.querySelector("#chart"), options);
      //chart.updateOptions(options);
      //chart.updateSeries(mydata);
    }
    
    chart.render();
  });
}

var urlParams = new URLSearchParams(window.location.search);
var deveui = urlParams.get('deveui');
var alias = urlParams.get('alias');
var property = urlParams.get('property');
var start = urlParams.get('start');
var stop = urlParams.get('stop');
var minmax = urlParams.get('minmax') || "0,0";

range="";
if (start == null) {
  var dstart = moment({hour: 0});
  var start = dstart.utc().format('YYYY-MM-DDTHH:mm:ss[Z]');
  range = range + "&start=" + start;
}

if (stop == null) {
  var dstop = moment();
  var stop = dstop.utc().format('YYYY-MM-DDTHH:mm:ss[Z]');
  range = range + "&stop=" + stop;
}

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

drawGraph(deveui, alias, property, start, stop, minmax, true);
