{% extends "layout.jinja2" %}

{% block extra_links %}
<link href="{{request.static_url('c2cgeoportal_admin:node_modules/jstree/dist/themes/default/style.min.css')}}" rel="stylesheet">
<link href="{{request.static_url('c2cgeoportal_admin:static/layertree.css')}}" rel="stylesheet">
{% endblock extra_links %}

{% block extra_scripts %}
<script type="text/javascript" src="{{request.static_url('c2cgeoportal_admin:node_modules/jstree/dist/jstree.js')}}"></script>
<script type="text/javascript" src="{{request.static_url('c2cgeoportal_admin:node_modules/jstreegrid/jstreegrid.js')}}"></script>
<script type="text/javascript" src="{{request.static_url('c2cgeoportal_admin:node_modules/jquery.scrollintoview/jquery.scrollintoview.js')}}"></script>
{% endblock extra_scripts %}

{% block content %}
<div id="layertree" class="container-fluid">
    <div id="toolbar">
      <div class="btn-group">
        {% if limit_exceeded %}
        <button id="layertree-expand" type="button" class="btn btn-default"><span class="glyphicon glyphicon-chevron-down"></span> {{_("Expand all")}}</button>
        {% endif %}
        <button id="layertree-collapse" type="button" class="btn btn-default"><span class="glyphicon glyphicon-chevron-up"></span> {{_("Collapse all")}}</button>
      </div>
      <div class="btn-group">
        <a id="layertree-ordering" class="btn btn-default" href="{{request.route_url('layertree_ordering')}}"><span class="glyphicon glyphicon-sort"></span> {{_("Edit themes order")}}</a>
      </div>
    </div>

    <div id="tree"></div>

    <script type="text/javascript">
    $(function () {
      const $jstree = $('#tree').jstree({
        core: {
          data: function(node, callback) {
            var url = "{{ request.route_url('layertree_children') }}";
            if (node.id != '#') {
              url += "?group_id=" + node.data.id + "&path=" + node.id;
            }
            $.ajax({ url: url })
            .done(function(data) {
              callback.call(this, data.map(function(item) {
                return {
                  id: item.path,
                  text: '&nbsp;' + item.name,
                  icon: 'glyphicon icon-' + item.item_type,
                  children: ['theme', 'group'].indexOf(item.item_type) != -1,
                  data: item
                };
              }));
            })
          },
          themes: {
            dots: false
          },
        },
        plugins: ["grid", "wholerow", "state"],
        grid: {
          height: $(window).height() - $('nav').height() - 100,
          width: '100%',
          columns: [
            {
              header: '&nbsp;',
              headerClass: 'actions',
              columnClass: 'actions',
              cellClass: 'cell-content',
              wideCellClass: 'wideCellClass',
              valueClassPrefix: 'valueClassPrefix',
              wideValueClass: 'wideValueClass',
              wideValueClassPrefix: 'wideValueClassPrefix',
              value: function(node) {
                var content = '\
                  <div class="btn-group dropdown">\
                    <button type="button" class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown" data-target="item-' + node.id + '-actions" aria-haspopup="true" aria-expanded="false">\
                      <span class="caret"></span>\
                    </button>\
                    <ul id="item-' + node.id + '-actions" class="dropdown-menu">';

                node.data.actions.forEach(function(action) {
                  if (action.confirmation || action.method) {
                    content += '\
                      <li>\
                        <a class="c2cgeoform-item-action c2cgeoform-action-ajax ' + action.name + ' ' + action.css_class + '"\
                           href="#"\
                           data-url="' + action.url + '"\
                           data-method="' + action.method + '"\
                           data-confirmation="' + action.confirmation + '">\
                           <span class="' + action.icon + '"></span>\
                           ' + action.label + '\
                        </a>\
                      </li>';
                  } else {
                    content += '\
                      <li>\
                        <a class="c2cgeoform-item-action ' + action.name + ' ' + action.css_class + '"\
                           href="' + action.url + '">\
                           <span class="' + action.icon + '"></span>\
                           ' + action.label + '\
                        </a>\
                      </li>';
                  }
                });

                content += '\
                    </ul>\
                  </div>';

                return content
              }
            },
            {
              header: 'Id',
              cellClass: 'cell-content',
              value: 'id'
            },
            {
              header: 'Name',
              cellClass: 'cell-content',
              tree: true
            },
            {
              header: '{{_('Name ({})').format(request.locale_name)}}',
              cellClass: 'cell-content',
              value: 'translated_name'
            },
            {
              header: '{{_('Description')}}',
              cellClass: 'cell-content',
              value: 'description'
            }
          ]
        }
      });

      // on click do not select but toggle
      $jstree.on('select_node.jstree', function (e, data) {
        $jstree.jstree(true).deselect_node(data.node);
        if (!$jstree.jstree(true).is_leaf(data.node)) {
          $jstree.jstree(true).toggle_node(data.node);
        }
      });
      // prevent toggle on non tree columns
      $jstree.on("select_cell.jstree-grid", function(event, data) {
        if (data.column != 'name') {
          event.preventDefault();
        }
      });

      var bindEvents = function(node_id) {
        const $column = $($jstree.jstree(true)._domManipulation.columns[0]);
        const $cell = $column.find('.jstree-grid-cell[data-jstreegrid="' + node_id + '"]');
        const $dropdown = $cell.find('.dropdown');

        // scroll on dropdown when shown
        $dropdown.on("shown.bs.dropdown", function () {
          $(this).children(".dropdown-menu").scrollintoview({viewPadding: 5});
          console.log('scrollintoview');
        });

        $dropdown.find('a.c2cgeoform-action-ajax').on('click', function(e) {
          var execute = function() {
            $.ajax({
              url: $(this).data('url'),
              type: $(this).data('method'),
              success: function(data) {
                if (this.type == 'DELETE') {
                  //$grid.bootstrapTable('refresh');
                  $jstree.jstree(true).delete_node(node_id);
                } else {
                  window.location = data.redirect;
                }
              }
            });
          }.bind(this);

          if ($(this).data('confirmation')) {
            if (window.confirm($(this).data('confirmation'))) {
              execute();
            }
          } else {
            execute();
          }

        });

        const node = $jstree.jstree(true).get_node(node_id);
        node.children.forEach(bindEvents);
      };

      $jstree.on("render_cell.jstree-grid", function(event, data) {
        if (data.column == '&nbsp;') {
          bindEvents(data.node.attr('id'));
        }
      });

      $("#layertree-expand").on('click', function() {
        $jstree.jstree(true).open_all();
      });

      $("#layertree-collapse").on('click', function() {
        $jstree.jstree(true).close_all();
      });

      $(window).resize(function() {
        $('.jstree-grid-wrapper').height($(window).height() - $('nav').height() - $('#toolbar').height() - 50);
        $('.jstree-grid-wrapper').width('100%');
      });
    });
    </script>

</div>

{% endblock content %}
