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

{% block filter %}{% if reportclass.filterable %}
&nbsp;<span id="filterform">
<span id="curfilter"></span>
&nbsp;
<div class="input-group d-inline-flex w-auto">
<input id="addsearch" class="form-control ps-2 pe-2" 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"
  type="button" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans 'Filter editor' %}">
  <i class="fa fa-search"></i>
</button>
	{% if reportclass.filterable %}{% 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}}
<script>

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 preferences = {{preferences|json}};
var resizing;
var editrow;
var editcol;
var currency = "";

{% if reportclass.hasTimeBuckets %}var numbuckets = {{request.report_bucketlist|length}};
{% endif %}

var actions = { {% for i in actions %}
   "{{ i.name|escape }}": function() { {{ i.function|safe }} }{% if not forloop.last %},{% endif %}{% endfor %}
   };

function displayGrid(load) {
  $(document).keydown(function(e) {
    // Check if Ctrl key is pressed and the 'A' key is pressed
    if (e.ctrlKey && e.key === 'a') {
        e.preventDefault();  // Prevent default behavior (selecting all text)
        // Get all row IDs
        var rowIds = $("#grid").jqGrid('getDataIDs');
        // Get the array of currently selected row IDs
        var selectedRowIds = $("#grid").jqGrid('getGridParam', 'selarrrow');

        // Loop through all row IDs
        for (var i = 0; i < rowIds.length; i++) {
            var rowId = rowIds[i];

            // Check if the row is already selected
            if ($.inArray(rowId, selectedRowIds) === -1) {
                // Select the row if it's not already selected
                $("#grid").jqGrid('setSelection', rowId);
            }
        }
        // After selecting all rows, select the header checkbox
        $("#grid").closest('div.ui-jqgrid').find('input[type="checkbox"]').prop('checked', true);
    }
  });
  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: (load || load === undefined) ? "json" : "local",
	  jsonReader : {repeatitems:false},
    colModel:[{{colmodel|safe}}],
   	rowNum: {{request.pagesize}},
    rowList: [
      {{request.pagesize}}+":"+{{request.pagesize}},
      (5*{{request.pagesize}})+":"+(5*{{request.pagesize}}),
      (10*{{request.pagesize}})+":"+(10*{{request.pagesize}}),
      "9999999:{% trans "All" %}"
      ],
   	autoencode: true,{% if is_popup %}
    onSelectRow: grid.setSelectedRow,{% elif reportclass.editable and haschangeperm %}
    cellEdit: true,
    cellsubmit: 'clientArray',
    editurl: location.pathname,
    afterEditCell: grid.afterEditCell,
    beforeSaveCell: upload.select,{% else %}
    onSelectRow: null,
    singleSelectClickMode: "toggle",
    multiselect: false, {% endif %}
    pager: {% if reportclass.isTreeView %} null {% else %} '#gridpager' {% endif %},
    iconSet: "fontAwesome",
    guiStyle: "bootstrap5Primary",
    viewrecords: true,
    pagingDuringEditing: "cancel",
    sortingDuringEditing: "cancel",
    reloadingDuringEditing: "cancel",
    multiSort: true,
    headertitles:true,
    maxSortColumns: 3,
    viewSort: true,
    sortorder: "{{sord}}",
    sortname: "{{sidx}}",
    page: {{page}},
    hidegrid: false,
    resizeStop: grid.saveColumnConfiguration,
    scrollRows: true,
    onSortCol: grid.saveColumnConfiguration,
    onPaging: grid.saveColumnConfiguration,
    //scroll: 1,      // Enables scrolling over all records, instead of paging. But not compatible with frozen columns.
    sortable: true, // Allows columns to be dragged and dropped between positions. But not compatible with frozen columns
    autowidth: true,
    postData: initialfilter ? {filters: JSON.stringify(initialfilter)} : {},
    search : true,
    shrinkToFit: false,
    searching: {
      multipleSearch: true,
      multipleGroup: true,
      closeOnEscape: true,
      searchOnEnter: true,
      searchOperators: true,
      zIndex: 5000,
      width: 700
    },
    gridComplete: function() {
      let gridCells = document.querySelectorAll('#grid td');
      for (let elem of gridCells) {
        if (!elem.hasAttribute('data-bs-toggle') && elem.scrollWidth > elem.clientWidth) {
          elem.setAttribute('data-bs-toggle', 'tooltip');
          elem.setAttribute('data-bs-title', elem.textContent);
          elem.setAttribute('data-bs-placement', 'left');
        }
      }
      var gridTooltipTriggerList = document.querySelectorAll('#grid [data-bs-toggle="tooltip"]');
      window.gridTooltipList = [...gridTooltipTriggerList].map(
        el => new bootstrap.Tooltip(el, {
          container: 'body',
          trigger : 'hover',
          delay: el.hasAttribute("data-bs-delay") ? JSON.parse(el.getAttribute("data-bs-delay")) : { "show": 500, "hide": 1000 }
        })
      );
    },
    loadError: function(xhr,st,err) {
      if (xhr.status == 401) {
        location.reload();
        return;
      }
      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 reportclass.editable and reportclass.multiselect and not is_popup and hasaddperm %}
    multiselect: true,
    multiboxonly: false,
    noCellSelection: true,
    onSelectRow: function(rowid, status, e) {
      var selection = $(this).jqGrid('getGridParam','selarrrow').slice(); //this makes this list a static list of values
      grid.markSelectedRow(selection.length);
    },
    formatCell: function(rowid, cellname, value, iRow, iCol) {
      editrow = iRow;
      editcol = iCol;
      return value;
    },
    beforeSelectRow: function (rowid, e) {
    	var $this = $(this), rows = this.rows,
            // get id of the previous selected row
            startId = $this.jqGrid('getGridParam', 'selrow'),
            startRow, endRow, iStart, iEnd, i;

      if (!e.shiftKey && !e.ctrlKey && !e.target.matches('[type="checkbox"]')){
          $this.jqGrid('resetSelection');
      }

      if (!e.shiftKey) {
            return true;
        } else if (startId) {

        	startRow = rows.namedItem(startId);
            endRow = rows.namedItem(rowid);
            rowidIndex = endRow.rowIndex;
        	var selRowIds = $this.jqGrid("getGridParam", "selarrrow");
        	iStart = startRow.rowIndex;
            iEnd = endRow.rowIndex;

            if (iStart == iEnd) {
            	if ($.inArray(rows[iStart].id, selRowIds) >= 0) {
        			$this.jqGrid('setSelection', rows[iStart].id, false);
        		}
            }

            for (i = Math.min(iStart, iEnd); i <= Math.max(iStart, iEnd); i++) {
                if (i != rowidIndex) {
             	if ($.inArray(rows[i].id, selRowIds) < 0) {
                 	$this.jqGrid('setSelection', rows[i].id, false);
                 }
                }
            	else {
            		if ($.inArray(rows[i].id, selRowIds) >= 0) {
            			$this.jqGrid('setSelection', rows[i].id, false);
            		}
            	}
            }
        }
        return true;
    },{% endif %}
    loadComplete: function(data) {
    	{% if reportclass.message_when_empty %}
    	$("#grid_empty_message").remove();
    	if (data.records == 0 && $(this).getGridParam("postData").filters === undefined)
    		$(this).parent().append(
    			`<div id="grid_empty_message" style="text-align:center; margin-top:5em">
    			{% include reportclass.message_when_empty %}
    			</div>`
    			);
    	{% endif %}
    	$('#curerror').html("");
      upload.restoreSelection();
    },
    {% 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;
            }
          }
        },
      isnull: {
          operand: "is null",
          text: "is null",
          filter: function (options) {
            var v = options.item[options.cmName];
            if (v === undefined || v === null || v === "") {
              return true;
            }
          }
        },
    },
    height: {% if reportclass.height %}
          {% if not reportclass.variableheight or not preferences.details or preferences.details == "bottom" %}
            {% if preferences.height %}{{preferences.height}}{% else %}{{reportclass.height}}{% endif %}
          {% else %}
            Math.max(150, $(window).height() - $("#grid").offset().top - {{reportclass.heightmargin}})
          {% endif %}
        {% else %}
          Math.max(150, $(window).height() - $("#grid").offset().top - {{reportclass.heightmargin}})
        {% endif %}
    }).on("jqGridRemapColumns", function() {grid.saveColumnConfiguration()});
    {% if reportclass.frozenColumns > 0 %}
  jQuery("#grid").jqGrid('setFrozenColumns');{% endif %}{% if reportclass.multiselect and not is_popup %}
  $('#cb_grid.cbox').click(grid.markAllRows);{% endif %}{% if reportclass.editable and haschangeperm %}
  $("th").bindFirst('click', upload.validateSort);{% endif %}
  {% if reportclass.height %} {% if not reportclass.variableheight or not preferences.details or preferences.details != "bottom" %}$("#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 %}
  var curfilter = $("#curfilter");
  grid.getFilterGroup($("#grid"), initialfilter, true, curfilter);
  }

  $(function() {
    {% if reportclass.hasTimeBuckets and not bucketnames %}
    $('#curerror').html("{% trans 'Error: Missing time buckets or bucket dates' %}");
  {% else %}
  {% block afterPageLoad %}displayGrid();{% endblock %}
  {% endif %}
  $("#grid").on('input', function(event) {
    // to prevent firefox from triggering save/undo on checkbox select
    if (!$(event.target).parent().hasClass('td_cbox')) {
      $("#save").removeClass("btn-primary btn-danger").addClass("btn-danger").prop("disabled", false);
      $("#undo").removeClass("btn-primary btn-danger").addClass("btn-danger").prop("disabled", false);
    }
	});

	$(window).bind('resize', function() {
    var h = $(window).height() - $("#grid").offset().top - 63;
    if (h < 150) h = 150;
    $("#grid")
     .setGridWidth($('#content-main').width()){% if not reportclass.height %}
     .setGridHeight(h){% 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'));
	});

  $("#actionsul li a, button#actions1").click(function(event){
    $("#actions1 span").text($(this).text());
    $("#actions").val($(this).prop('name'));
    grid.runAction($(this).prop('name'));
    event.preventDefault();
  });

  {% if reportclass.editable and reportclass.multiselect and not is_popup and hasaddperm %}
  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|capfirst %}{% 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|capfirst %}{% trans "Undo" %}{% endfilter %}
</button>
{% if actions %}
<form class="form-addon d-inline" method="get">
{% if actions|length == 1 %}
  <input type="hidden" name="actions" id="actions" value="{{ actions.0.name }}">
  <button class="btn btn-primary" disabled id="actions1" name="{{ actions.0.name|escape }}">
  {% filter force_escape|capfirst %}{% trans actions.0.label|capfirst %}{% endfilter %}
  </button>
{% else %}
  <input type="hidden" name="actions" id="actions" value="">
  <div class="dropdown d-inline">
      <button disabled class="d-inline w-auto dropdown-toggle form-control" type="button" name="actions1" id="actions1" data-bs-toggle="dropdown" aria-expanded="false">
      <span>{% trans "select action"|capfirst %}</span>
      </button>
      <ul class="dropdown-menu" id="actionsul">
      {% for i in  actions %}
        <li><a class="dropdown-item" name="{{ i.name|escape }}">{% trans i.label|capfirst %}</a></li>
      {% endfor %}
      </ul>
  </div>
{% endif %}
</form>
{% endif %}
{% endif %}
{% endblock save_undo_buttons %}
</div>

<div id="toolicons" class="col-auto ms-auto ver-align-middle">{% block actions %}
{% if hasaddperm %}<button class="btn btn-sm btn-primary" onclick="location.href='{{request.prefix}}/data/{{model|app_label}}/{{model|object_name|lower}}/add/{% if is_popup %}?_popup=1{% endif %}'" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans "Create new object"|escape %}" ><span class="fa fa-plus"></span></button>
{% endif %}{% if hasaddperm and not is_popup and reportclass.canDuplicate %}<button class="btn btn-sm btn-primary"  disabled id="copy_selected" onclick="grid.showCopy()" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans 'Copy selected objects'|capfirst|escape %}" ><span class="fa fa-copy"></span></button>
{% endif %}{% if haschangeperm and not is_popup %}<button class="btn btn-sm btn-primary" id="edit_selected" disabled onclick="grid.showUpdate('{{request.prefix}}/data/{{model|app_label}}/{{model|object_name|lower}}/')" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans "Update objects"|escape %}" ><span class="fa fa-edit"></span></button>
{% endif %}{% if hasdeleteperm and not is_popup %}<button class="btn btn-sm btn-primary" id="delete_selected" disabled data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans 'Delete selected objects'|capfirst|escape %}" onclick="grid.showDelete('{{request.prefix}}/data/{{model|app_label}}/{{model|object_name|lower}}/')" ><span class="fa fa-minus"></span></button>
{% endif %}{% if reportclass.hasTimeBuckets %}<button class="btn btn-sm btn-primary" onclick="grid.showBucket()" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans 'set time horizon'|capfirst|force_escape %}" id="bucketconfig"><span class="fa fa-clock-o"></span></button>
{% endif %}{% if hasaddperm %}<button class="btn btn-sm d-none d-md-inline-block btn-primary" id="csvimport" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans 'Import CSV or Excel file'|capfirst|force_escape %}" onclick="import_show('', undefined, true)"><span class="fa fa-arrow-up"></span></button>
{% endif %}<button class="btn btn-sm btn-primary" onclick="grid.showExport(true,{{ scenario_permissions }})" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans 'export as CSV or Excel file'|capfirst|force_escape %}"><span class="fa fa-arrow-down"></span></button>
<button id="customize" class="btn btn-sm btn-primary" onclick="grid.showCustomize(false);" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans 'customize'|capfirst|force_escape %}"><span class="fa fa-wrench"></span></button>{% endblock %}
</div>

</div>

{% block table %}
<div class="row" id="main-row" style="text-align: center;">
<div id="content-main" class="col" style="min-height: 150px; margin-top: 0.7em">
<table id="grid" class="table table-striped" style="background-color: white"></table>
<div id="gridpager"></div>
</div>
<span id="resize-handle" class="fa fa-bars handle" style="display: none;"></span>
</div>
{% endblock %}

{% block after_table %}{% endblock %}

{% if reportclass.hasTimeBuckets %}
{% include "admin/subtemplate_timebuckets.html" %}
{% endif %}
{% endblock %}
