<div data-dojo-type="dijit.layout.BorderContainer" style="width:100%;height:100%" data-dojo-props="gutters: false, toggleSplitterOpen: true, baseClass: 'NoGutter'">
  {% block actions_static_pane %}
  <div data-dojo-type="dijit.layout.ContentPane" data-dojo-props="region: 'top', splitter: false" style="background-color: white;height: 60px;" doLayout="false">
    {% block actions_static_buttons %}
    {% if add_url %}
    <div class="gridAdd left">
      <button id="datagridBtn_{{ module_name }}_Add" data-dojo-type="dijit.form.Button" type="button">
          {% blocktrans with name=verbose_name %}Add {{ name }}{% endblocktrans %}
      <script type="dojo/method" data-dojo-event="onClick" data-dojo-args="evt">
          editObject('{% trans "Add"|escapejs %} {{ verbose_name }}', '{{ add_url }}', [this,]);
      </script>
      </button>
    </div>
    {% endif %}
    {% endblock %}
    {% for btn in hook_buttons %}
      <button id="datagridBtn_{{ module_name }}_{{ btn.name }}" data-dojo-type="dijit.form.Button" type="button">
          {% if btn.icon %}
	  <img src="{{ STATIC_URL }}{{ btn.icon }}">
	  {% endif %}
          <p>{{ btn.verbose_name }}</p>
      <script type="dojo/method" data-dojo-event="onClick" data-dojo-args="evt">
          {{ btn.onclick|safe }}
      </script>
      </button>
    {% endfor %}
    <span class="clear"></span>
  </div>
  {% endblock %}
  <div class="gridDiv" id="dgrid_{{ module_name }}" data-dojo-type="dijit.layout.ContentPane" data-dojo-props="region: 'center'"></div>
  <div data-dojo-type="dijit.layout.ContentPane" data-dojo-props="region: 'bottom', splitter: false" style="border: 1px solid #ddd;background-color: white;height: 40px;display: none;" doLayout="false">

      <div class="actionsPane" data-dojo-type="dijit.layout.ContentPane" style="background-color: white;" doLayout="false">
        {% block actions_pane %}
        {% endblock %}
        <span class="clear"></span>
      </div>
  </div>
</div>
<div data-dojo-type="dijit.layout.ContentPane">
    <script type="dojo/method">
    var cpane = this;
require([
    "dojo/_base/declare",
    "dojo/dom",
    "dojo/dom-class",
    "dojo/dom-construct",
    "dojo/dom-style",
    "dojo/query",
    "dojo/request/xhr",
    "dstore/Memory",
    "dstore/Rest",
    "dstore/Tree",
    "dgrid/OnDemandGrid",
    "dgrid/Keyboard",
    "dgrid/Selection",
    "dgrid/Tree",
    "dgrid/extensions/DijitRegistry",
    "dgrid/extensions/ColumnResizer",
    "dijit/registry",
    "dijit/form/Button",
    "dijit/Tooltip"
    ], function(
    declare,
    dom,
    domClass,
    domConstruct,
    domStyle,
    query,
    xhr,
    Memory,
    Rest,
    TreeStore,
    Grid,
    Keyboard,
    Selection,
    Tree,
    DijitRegistry,
    ColumnResizer,
    registry,
    Button,
    Tooltip) {

    var columns, actions;
    xhr.get('{{ structure_url }}', {
        sync: true,
        handleAs: 'text'
    }).then(function(data) {
        columns = eval('(' + data + ')');
        for(var key in columns) {
            if(typeof columns[key] == 'string') {
                columns[key] = eval('(' + columns[key] + ')')
            }
	    var funcs = {'formatter': 1, 'renderCell': 1};
            for(var func in funcs) {
                if(typeof columns[key][func] == 'string') {
                    columns[key][func] = eval('(' + columns[key][func] + ')')
                }
            }
            if(columns[key].shouldExpand !== undefined){
                columns[key].shouldExpand = function() { return true };
            }
        }
    });

    var defaultOnSelect = function(evt, actionName, action) {
        var numrows = 0;
        for(var key in evt.grid.selection) numrows++;
        if(numrows > 1 || numrows == 0) {
            query(".grid" + actionName).forEach(function(item, idx) {
                domStyle.set(item, "display", "none");
            });
        } else {
            query(".grid" + actionName).forEach(function(item, idx) {
                domStyle.set(item, "display", "block");
            });
        }
        if(action.on_select_after !== undefined) {
          action.on_select_after(evt, actionName, action);
        }
    };

    xhr.get('{{ actions_url }}', {
        sync: true,
        handleAs: 'json'
    }).then(function(data) {
        actions = data;
        var funcs = {'on_select': 1, 'on_select_after': 0, 'on_click': 1};
        for(var key in actions) {
            for(var func in funcs) {
              if(actions[key][func] === undefined && funcs[func] == 1) {
                actions[key][func] = defaultOnSelect;
              } else {
                var funceval = eval('(' + actions[key][func] + ')');
                actions[key][func] = funceval;
              }
            }

            var pane = query(".actionsPane", cpane.domNode.parentNode)[0];

            var n = domConstruct.create("div", null, pane);
            domClass.add(n, ["grid" + key, "left"]);
            domStyle.set(n, "display", "none");

            var but = new Button({
                'id': "datagridActionBtn_{{ module_name }}" + key,
                'label': actions[key]['button_name'],
                'onClick': actions[key]['on_click']
            });

            if(actions[key]['tooltip'] !== undefined) {
              new Tooltip({
                'position': ['above'],
                'connectId': [but.domNode],
                'label': actions[key]['tooltip']
              });
            }

            but.placeAt(n);

        }
    });

    var store = new (declare([Rest, TreeStore]))({
        target: "{{ resource_url }}{{ datagrid_filters|escapejs }}",
        headers: {"X-Requested-From": "WebUI"},
	useRangeHeaders: true,
        getChildren: function(object){
	    col = new Memory({});
	    col.setData(object.children);
	    return col;
        },
        mayHaveChildren: function(parent){
            return parent.children !== undefined && parent.children.length > 0;
        }
    });

    var StandardGrid = declare([Grid, Tree, Selection, Keyboard, ColumnResizer]);
    var griddiv = query(".gridDiv", cpane.domNode.parentNode)[0];
    var grid = new StandardGrid({
        collection: store.getRootCollection(),
        columns: columns,
	loadingMessage: '{% trans "Loading..."|escapejs %}',
	noDataMessage: '{% trans "No entry has been found"|escapejs %}',
	shouldExpand: function(){ return true; }
        }, griddiv);
    griddiv.grid = grid;

    {% if refresh_time %}
    grid.on("dgrid-refresh-complete", function(evt) {

      setTimeout(function() {
        var selected = [];
        var rows = [];
        for(var id in grid.selection){
          selected.push(id);
          rows.push(grid.row(id));
        }
        grid.refresh();
        grid.clearSelection();
        for(var id in selected) {
            grid.select(selected[id]);
        }
        selectionCheck({rows: rows, grid: grid});
      }, {{ refresh_time }});

    });
    {% endif %}

    grid.on("dgrid-error", function(event) {
      if(event.error.response.status == 401) {
        window.location = '/';
      }
      grid.contentNode.innerHTML = event.error.message;
    });

    {% if double_click %}
{{ double_click|safe }}
    {% endif %}

    var selectionCheck = function(evt) {
        var numselected = 0;
        for(key in grid.selection) numselected++;
        for(key in actions) {
            var func = actions[key]['on_select'];
            try {
              func(evt, key, actions[key]);
            } catch(e) {
              console.log(e);
            }
        }

        // Disable actionsPane if there are no selected rows
        var actpane = query(".actionsPane", cpane.domNode.parentNode)[0];
        var border = registry.getEnclosingWidget(actpane.parentNode.parentNode);
        if(numselected > 0) {
            domStyle.set(actpane.parentNode, "display", "block");
        } else {
            domStyle.set(actpane.parentNode, "display", "none");
        }
        border.layout();
    };
    grid.on("dgrid-select, dgrid-deselect", function(evt) {
        selectionCheck(evt);
    });
    grid.clearSelection();
    //selectionCheck();

});
</script>
</div>
