Date.prototype.getWeek = function () {
  var date = new Date(this.getTime());
  date.setHours(0, 0, 0, 0);
  // Thursday in current week decides the year.
  date.setDate(date.getDate() + 3 - ((date.getDay() + 6) % 7));
  // January 4 is always in week 1.
  var week1 = new Date(date.getFullYear(), 0, 4);
  // Adjust to Thursday in week 1 and count number of weeks from date to week1.
  return (
    1 +
    Math.round(
      ((date.getTime() - week1.getTime()) / 86400000 -
        3 +
        ((week1.getDay() + 6) % 7)) /
        7
    )
  );
};
var days = function (month, year) {
  return new Date(year, month, 0).getDate();
};
function getDivider(){
  let datetype = $("#dateType").val();
  switch(datetype){
    case'day':
    return 1;
    case'month':
    return 30;
    case'week':
    return 7;
  }
}
function loadTable(filter) {
  //console.log(filter);
  $.ajax({
    url: "/ajax/get/statistic/feature",
    dataType: "json",
    type: "GET",
    delay: 250,
    data: filter,
  }).done(function (jsonData) {
    jsonData.forEach((e) => {
      if(e.unit=="min"){
        e.measured = parseInt(e.measured/60);
        e.measuredAVG = (e.measured/getDivider()).toFixed(2)+" "+e.unit;
        e.measured = e.measured+" "+e.unit;
        e.balance = parseInt(e.balance);
        e.balanceAVG = parseInt(e.balance/getDivider());
      }else{
        e.measured = parseInt(e.measured);
        e.measuredAVG = (e.measured/getDivider()).toFixed(2)+" "+e.unit;
        e.measured = e.measured+" "+e.unit;
        e.balance = parseInt(e.balance);
        e.balanceAVG = parseInt(e.balance/getDivider());
      }
    });
    $("#jsGrid").jsGrid({
      width: "100%",
      height: "300px",
      readonly: true,
      sorting: true,
      paging: true,
      pageSize: 50,
      data: jsonData,
      fields: [
        { name: "feature", type: "text", width: 100, title: "Megnevezés" },
        { name: "measured", type: "text", title: "Mért" },
        { name: "measuredAVG", type: "number", width: 75, title: "Mért átlag" },
        { name: "balance", type: "number", width: 75, title: "Bevétel" },
        { name: "balanceAVG", type: "number", width: 75, title: "Bevétel átlag" },
      ],
    });
  });
}
$("button.refreshData").on("click", function (ev, picker) {
  let dateText = $(".datepicker").val();
  $(this).datepicker("setDate", new Date(dateText));
  let date = new Date(dateText);
  let dateType = $("#dateType").val();
  let fID = $("#featureType").val();
  //console.log(date.getUTCDay());
  var urlParams = new URLSearchParams(window.location.search);
  let _id = urlParams.get("econid");
  switch (dateType) {
    case "year":
      loadGraph({featureID:fID, year: date.getFullYear() });
      break;
    case "month":
      loadGraph({
        featureID:fID,
        year: date.getFullYear(),
        month: date.getMonth() + 1,
      });
      break;
    case "week":
      loadGraph({featureID:fID, year: date.getFullYear(), week: date.getWeek() });
      break;
    case "day":
      loadGraph({
        featureID:fID,
        year: date.getFullYear(),
        month: date.getMonth() + 1,
        day: date.getDate(),
      });
      break;
  }
});
$(".datepicker").daterangepicker({
  singleDatePicker: true,
  firstDay: 1,
  locale: {
    format: "YYYY-MM-DD",
    separator: " - ",
    firstDay:1,
    applyLabel: "Mentés",
    cancelLabel: "Mégse",
    startView: "months", 
    minViewMode: "months",
    daysOfWeek: ["V", "H", "K", "Sze", "Cs", "P", "Szo"],
    monthNames: [
      "Január",
      "Február",
      "Március",
      "Április",
      "Május",
      "Június",
      "Július",
      "Augusztus",
      "Szeptember",
      "Október",
      "November",
      "December",
    ],
  },
});
function loadGraph(filter) {
  // Sales graph chart
  $("#line-chart").remove();
  $(".card-body.line-Chart").append(
    `<canvas class="chart chartjs-render-monitor" id="line-chart" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 100%; display: block; width: 674px;" width="674" height="250"></canvas>`
  );
  var salesGraphChartCanvas = $("#line-chart").get(0).getContext("2d");
  //filter.featureID = 0;
  // $('#revenue-chart').get(0).getContext('2d');
  let fID = $("#statType").val();
  $.ajax({
    url: "/ajax/get/statistic/feature/"+fID,
    dataType: "json",
    type: "GET",
    delay: 250,
    data: filter,
  }).done(function (jsonData) {
    let labelss = [];
    var money = [];
    var avarages = [];
    var data = $.map(jsonData, function (obj) {
      //let name = `${obj.city} - ${obj.title}`;
      labelss.push(obj.value*1);
      if(obj.unit=="min"){
        obj.measured = obj.measured/60;
      }
      money.push(obj.measured);
      //avarages.push(obj.balance);
    });
    //data = [labels,money];
    var salesGraphChartData = {
      labels: labelss,
      datasets: [
        {
          label: "Átlag",
          fill: true,
          borderWidth: 2,
          lineTension: 0,
          spanGaps: true,
          borderColor: "#ff0000",
          pointRadius: 3,
          pointHoverRadius: 7,
          pointColor: "#ff0000",
          pointBackgroundColor: "#ff0000",
          data: money,
        },
      ],
    };
    var salesGraphChartOptions = {
      maintainAspectRatio: false,
      responsive: true,
      legend: {
        display: false,
      },
      scales: {
        xAxes: [
          {
            ticks: {
              fontColor: "#efefef",
            },
            gridLines: {
              display: false,
              color: "#efefef",
              drawBorder: false,
            },
          },
        ],
        yAxes: [
          {
            ticks: {
              stepSize: 5000,
              fontColor: "#efefef",
            },
            gridLines: {
              display: true,
              color: "#efefef",
              drawBorder: false,
            },
          },
        ],
      },
    };
    // This will get the first returned node in the jQuery collection.
    // eslint-disable-next-line no-unused-vars
    
    var salesGraphChart = new Chart(salesGraphChartCanvas, {
      // lgtm[js/unused-local-variable]
      type: "bar",
      data: salesGraphChartData,
      options: salesGraphChartOptions,
    });
    
  });
  //salesGraphChartCanvas.update();
  //loadGraph2(filter);
}