{% extends "admin/base_site_nav.html" %}
{% load i18n %}

{% block filter %}{% if reportclass.filterable and not args.0 %}
&nbsp;<span id="filterform">
<span id="curfilter"></span>
&nbsp;
<div class="input-group d-inline-flex w-auto">
<input id="addsearch" class="form-control" placeholder="{% trans 'Filter' %}" role="searchbox"
  type="text" size="15" oninput="grid.showFieldList(this)" onkeydown="grid.keyDownSearch(event)">
<button class="input-group-text" onclick="event.stopPropagation(); grid.showFilter()" data-bs-offset="0,5"
  data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans "Filter editor" %}">
  <i class="fa fa-search"></i>
</button>
{% if reportclass.filterable and not args.0 %}{% include "common/snippet_favorites.html" with search=True %}{% endif %}
</div>
<div class="align-middle d-inline-flex" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-offset="0,5"
  data-bs-title="{% trans 'reset filters'|capfirst|force_escape %}">
  <div>
    <i id="resetfilter" onclick="grid.resetFilter()" class="fa fa-times fs-6" ></i>
  </div>
</div>
</span>
{% endif %}{% endblock %}

{% block extrahead %}{{block.super}}
{% if args.0 or mode == 'graph' %}
<script src="{{STATIC_URL}}js/d3.min.js"></script>
{% endif %}
<script>
var editrow;
var editcol;

{% block crosses %}function crosses (cellvalue, options, rowdata) {
  for (var i in cellvalue)
    if (i == 0) var res = cellvalue[i];
    else res += '<br>' + cellvalue[i];
  return res;
};{% endblock %}

var reportkey = '{{reportkey|safe}}';
var initialfilter{% if filters %} = {{filters|json}}{% endif %};
var favorites = {% if preferences.favorites %}{{preferences.favorites|json}}{% else %}{}{% endif %};
var default_sort = "{{default_sort|safe}}";
var resizing;
var editrow;
var editcol;
{% if reportclass.hasTimeBuckets %}var numbuckets = {{request.report_bucketlist|length}};
var timebuckets = [ {% for f in request.report_bucketlist %}{% if not forloop.first %},{% endif %}{'name':'{{f.name}}','startdate':'{{f.startdate|date:"DATETIME_FORMAT"}}','enddate':'{{f.enddate|date:"DATETIME_FORMAT"}}','history':{{f.history}}}{% endfor %} ];
{% endif %}var cross_idx = {{cross_idx|safe}};
var cross = [
{{cross_list|safe}}
];

$(function() {
  {% if reportclass.hasTimeBuckets and not bucketnames %}
  $('#curerror').html("{% trans 'Error: Missing time buckets or bucket dates' %}");
{% else %}
  jQuery("#grid").jqGrid({
   	url: (location.href.indexOf("#") != -1 ? location.href.substr(0,location.href.indexOf("#")) : location.href)
      + (location.search.length > 0 ? "&format=json" : "?format=json"),
	  datatype: "json",
	  jsonReader : {repeatitems:false},
   	colModel:[
      {{colmodel|safe}},{% if mode == "table" %}
      {"name":"columns","label":" ","sortable":false,"width":{% if preferences.label_width %}{{preferences.label_width}}{% else %}150{% endif %},"align":"left","formatter":grid.pivotcolumns,"search":false,"frozen":true,"title":false },
      {% for f in request.report_bucketlist %}{% if not forloop.first %},
      {% endif %}{name:'{{f.name|safe}}'{% if f.history %},label:'<i style="font-weight:normal">{{f.name|safe}}</i>',history:true{% else %},history:false{% endif %},startdate:'{{f.startdate|date:"DATETIME_FORMAT"}}',enddate:'{{f.enddate|date:"DATETIME_FORMAT"}}',sortable:false,width:90,align:'center',formatter:crosses,search:false,title:false,headerTitle:"{{f.startdate|date:"DATE_FORMAT"}} - {{f.enddate|date:"DATE_FORMAT"}}" }{% endfor %}
      {% else %}
      {"name":"graph","index":"graph","editable":false,"label":" ","title":false,"sortable":false,"formatter":"graph","searchoptions":{"searchhidden": true},"fixed":false}
      {% endif %}],{% if reportclass.editable and haschangeperm %}
    cellsubmit: 'clientArray',
    editurl: location.pathname,
    beforeSaveCell: upload.select,{% else %}
    onSelectRow: function() {$(this).resetSelection();},
    formatCell: function(rowid, cellname, value, iRow, iCol) {
      editrow = iRow;
      editcol = iCol;
      return value;
    },
    {% endif %}rowNum: {{request.pagesize}},
    rowList: [
      {{request.pagesize}}+":"+{{request.pagesize}},
      (5*{{request.pagesize}})+":"+(5*{{request.pagesize}}),
      (10*{{request.pagesize}})+":"+(10*{{request.pagesize}}),
      "9999999:{% trans "All" %}"
      ],
   	pager: '#gridpager',
    viewrecords: true,
    pagingDuringEditing: "cancel",
    sortingDuringEditing: "cancel",
    reloadingDuringEditing: "cancel",
    sortorder: "asc",
    iconSet: "fontAwesome",
    guiStyle: "bootstrap5Primary",
    hidegrid: false,
    gridComplete: function() { $("#tooltip").css("display", "none");},
    resizeStop: grid.saveColumnConfiguration,
    scrollRows: true,
    sortorder: "{{sord}}",
    sortname: "{{sidx}}",
    multiSort: true,
    headertitles:true,
    maxSortColumns: 3,
    viewSort: true,
    onSortCol: grid.saveColumnConfiguration,
    onPaging: grid.saveColumnConfiguration,
    autowidth: true,
	  shrinkToFit: {% if mode == "table" %}false{% else %}true{% endif %},
    searching: {
      multipleSearch: true,
      multipleGroup: true,
      closeOnEscape: true,
      searchOnEnter: true,
      searchOperators: true,
      zIndex: 5000,
      width: 700
    },
	  loadError: function(xhr,st,err) {
      if (xhr.status == 401) {
        location.reload();
        return;
      }
	    $('#load_grid').show();
	    if (xhr.status == 200) {
        $('#curerror').html("{{_('Warning: no data found')|escapejs}}");
        $('#grid').clearGridData();
      }
      else
        $('#curerror').html("{{_('Error')|escapejs}}" + ":&nbsp;" + xhr.status + "&nbsp;" + xhr.statusText);
    },{% if filters %}
    postData: {filters: JSON.stringify(initialfilter)},
    search : true,{% endif %}
    {% block extra_grid %}{% endblock %}
    customSortOperations: {
      win: {
        operand: "within",
        text: "within days",
        filter: function (options) {
          var v = options.item[options.cmName];
          if (v === undefined || v === null || v === "") {
            return true;
          }
        }
      },
      ico: {
          operand: "is child of",
          text: "is child of",
          filter: function (options) {
            var v = options.item[options.cmName];
            if (v === undefined || v === null || v === "") {
              return true;
            }
          }
        },
    },
	height: {% if reportclass.height %}{{reportclass.height}}{% else %}Math.max(150, $(window).height() - $("#grid").offset().top - {{reportclass.heightmargin}}){% endif %}
    });
  {% if mode == "table" %}jQuery("#grid").jqGrid('setFrozenColumns');
  {% endif %}{% if filters %}var curfilter = $("#curfilter");
  grid.getFilterGroup($("#grid"), initialfilter, true, curfilter);{% endif %}
  jQuery("#gridmode").click(function() {grid.displayMode("table");});
  jQuery("#graphmode").click(function() {grid.displayMode("graph");});{% if reportclass.editable and haschangeperm %}
  $("th").bindFirst('click', upload.validateSort);{% endif %}
  {% if reportclass.height %}$("#grid").gridResize({
     handles: 's', minHeight: {{reportclass.height}},
     resize: function() {
       // Save the configuration if we don't get any more resizing events in 200ms.
       clearTimeout(resizing);
       resizing = setTimeout(grid.saveColumnConfiguration, 200);
       }
     });
  {% endif %}
{% endif %}

	$(window).bind('resize', function() {
    {% if args.0 or mode == "graph" %}
    if ($("#grid").jqGrid('getGridParam','width') != $('#content-main').width()) {
      // Redraw the graph when the width changes
      var h = $(window).height();
      $("#graph").width($(window).width()-60).height(h>800 || h<550 ? 360 : h-450);
      clearTimeout(resizing);
      resizing = setTimeout(function(){
          $("#grid").trigger("reloadGrid");
          }, 200);
    }
    {% endif %}
    $("#grid")
      .setGridWidth($('#content-main').width())
      .setGridHeight({% if reportclass.heigth %}{{reportclass.heigth}}{% else %}$(window).height() - $("#grid").offset().top - {{reportclass.heightmargin}}{% endif %});
  });

	$("#horizonbucketsul li a").click(function(){
	  $("#horizonbuckets1").html($(this).text() + '  <span class="caret"><\/span>');
	  $("#horizonbuckets").val($(this).prop('name'));
	});

  $("#horizonunitul li a").click(function(){
    $("#horizonunit1").html($(this).text() + '  <span class="caret"><\/span>');
    $("#horizonunit").val($(this).prop('name'));
  });

  {% if reportclass.editable and haschangeperm %}
  if (isDragnDropUploadCapable()) {
    $("#content-main").on('dragover', function(e) {
      if (e.originalEvent.dataTransfer.types) {
        for (var i = 0; i < e.originalEvent.dataTransfer.types.length; i++) {
          if (e.originalEvent.dataTransfer.types[i] == "Files") {
            $("#content-main").addClass("dropfile");
            e.stopPropagation();
            e.preventDefault();
            }
        }
      }});
    $("#content-main").on('dragleave', function(e) {
  	  $("#content-main").removeClass("dropfile");
  	  e.stopPropagation();
  	  e.preventDefault();
      });
    $("#content-main").on('drop', function(e) {
      if (e.originalEvent.dataTransfer.files.length > 0) {
        import_show('', undefined, true, undefined, e.originalEvent.dataTransfer.files);
  	    e.preventDefault();
      }});
  }
  {% endif %}
});

</script>
{% endblock %}
{% block content %}
{% block before_table %}{% endblock %}

<div class="row">

<div id="save_undo" class="col-auto">
{% block save_undo_buttons %}
{% if not is_popup and reportclass.editable and haschangeperm %}
<button class="btn btn-primary" disabled id="save" onclick="upload.save()" title="{% trans 'save changes'|capfirst|force_escape %}"><i class="fa fa-spinner fa-spin d-none"></i>{% filter force_escape %}{% trans "Save" %}{% endfilter %}</button>
<button class="btn btn-primary" disabled id="undo" onclick="upload.undo()" title="{% trans 'undo changes'|capfirst|force_escape %}">{% filter force_escape %}{% trans "Undo" %}{% endfilter %}</button>
{% endif %}
{% endblock save_undo_buttons %}
</div>

<div id="toolicons" class="col-auto ver-align-middle ms-auto">{% block extra_toolicons %}{% endblock %}{% if reportclass.hasTimeBuckets and not args.0 %}
	<div class="btn-group" role="group">
		<button data-bs-toggle="tooltip" data-bs-placement="top" title="{% trans "display table"|capfirst|force_escape %}" class="btn btn-sm btn-primary{% if mode == 'table' %} active{% endif %}" type="button" id="gridmode" name="mode">
		  <span class="fa fa-table fa-lg" style="margin: 2px 0 3px 0;"></span>
		</button>
		<button data-bs-toggle="tooltip" data-bs-placement="top" title="{% trans "display graph"|capfirst|force_escape %}" class="btn btn-sm btn-primary{% if mode == 'graph' %} active{% endif %}" type="button" id="graphmode" name="mode">
		  <span class="fa fa-picture-o fa-lg fa-lg" style="margin: 2px 0 3px 0;"></span>
		</button>
	</div>
	{% endif %}
	{% if reportclass.hasTimeBuckets %}
	  <button class="btn btn-sm btn-primary" onclick="grid.showBucket()"
      data-bs-toggle="tooltip" data-bs-placement="top" title="{% trans 'set time horizon'|capfirst|force_escape %}">
	    <span class="fa fa-clock-o"></span>
	  </button>
  {% endif %}
  {% if reportclass.editable and haschangeperm %}
	    <button class="btn btn-sm d-none d-md-inline-block btn-primary" onclick="import_show('', undefined, true)"
        data-bs-toggle="tooltip" data-bs-placement="top" title="{% trans 'Import CSV or Excel file'|capfirst|force_escape %}">
        <span id="csvimport" class="fa fa-arrow-up"></span>
	    </button>
  {% endif %}
		  <button class="btn btn-sm btn-primary" onclick="grid.showExport(false,{{ scenario_permissions }})"
        data-bs-toggle="tooltip" data-bs-placement="top" title="{% trans 'export as CSV or Excel file'|capfirst|force_escape %}" >
		    <span class="fa fa-arrow-down"></span>
		  </button>
      <button class="btn btn-sm btn-primary" onclick="grid.showCustomize(true);"
        data-bs-toggle="tooltip" data-bs-placement="top" title="{% trans 'customize'|capfirst|force_escape %}" >
        <span class="fa fa-wrench"></span>
      </button>
	</div>
</div>

<div class="row">
	<div id="content-main" class="col-md-12" style="min-height: 150px; margin-top: 0.7em">
	 <table id="grid" class="table table-striped pivotgrid"></table>
	</div>
<div id="gridpager" class="col-md-12"></div>
</div>
{% block after_table %}{% endblock %}
{% if reportclass.hasTimeBuckets %}
{% include "admin/subtemplate_timebuckets.html" %}
{% endif %}
{% endblock %}
