{extends "../list.tpl"}

{block css append}
   <style>
      {$sizeSum = 0}
      {foreach $columns.fields as $name => $column}
      {if ($column.wpjAdmin and !isSuperuser()) or $column.visible == 'N'}
      {continue}
      {/if}
      {$sizeSum = $sizeSum + $column.size}
      {/foreach}
      {if $sizeSum > 0}{$singlePartRelSize = 100/$sizeSum}{else}{$singlePartRelSize = 10}{/if}
      {$partCounter = 0}
      {foreach $columns.fields as $name => $column}
      {if ($column.wpjAdmin and !isSuperuser()) or $column.visible == 'N'}
      {continue}
      {/if}
      .tdd-row > .tdd-column-{$column@index + 1} {
         left: {$singlePartRelSize*$partCounter}%;
         width: {$singlePartRelSize*$column.size}%;
      }

      {$partCounter = $partCounter + $column.size}
      {/foreach}
   </style>
{/block}

{block name="list-panel-class"}menu-list{/block}

{block addFilter}
    {* todo podle sekcí ?? *}
   {*<div class="filter-item">
       {if $smarty.get.opened == 'all'}
          <a class="btn btn-xs btn-ghost" href="launch.php?s={$view->getPageHandler()}&type={$view->getListName()}">
             <i class="bi bi-dash-circle m-r-1"></i>Sbalit vše
          </a>
       {else}
          <a class="btn btn-xs btn-ghost" href="launch.php?s={$view->getPageHandler()}&type={$view->getListName()}&opened=all">
             <i class="bi bi-plus-circle m-r-1"></i>Rozbalit vše
          </a>
       {/if}
   </div>*}
{/block}

{block "list-filter-pager"}
    {if $pager}
       <div class="filter-item">
          <span class="small text-muted">
              {$pager.total|number_format:0:".":" "}&nbsp;položek
          </span>
       </div>
    {/if}
{/block}

{block "list-filter-columns-settings"}{/block}

{block listTable}
   <div class="tdd-row thh-row">
       {foreach $columns.fields as $label => $column}
           {if ($column.wpjAdmin and !isSuperuser()) or $column.visible == 'N'}
               {continue}
           {/if}
          <div class="tdd-column tdd-column-{$column@index + 1} {$view->resolveCallable($column.class, $entry) nofilter}">
             <small>{$object->printHeaderLabel($column.title, $column)}&nbsp;</small>
          </div>
       {/foreach}
   </div>
   <div class="table">
       {foreach $SQL.menu as $menuID => $menu}
          <div data-node-id="{$menuID}">
             <div class="sections-root">
                <div class="tdd-row">
                   {* todo dynamic column index *}
                   <div class="tdd-column tdd-column-1">
                       <strong>{$menu.name}</strong>
                   </div>
                   <div class="tdd-column tdd-column-2">
                       {if isSuperuser() and $menuID}
                          <a href="javascript:nw('menu', {$menu.id}, '')">[{$menuID}] {if $menu.code}[{$menu.code}]{/if}</a>
                       {/if}
                   </div>
                   <div class="tdd-column tdd-column-5 columnBtns">
                      <div class="dropdown">
                         <a class="btn btn-success btn-block btn-sm dropdown-toggle" data-toggle="dropdown" id="newItemDropdown_{$menuID}">
                            <span class="bi bi-plus-lg m-r-1"></span>{'nestNewItem'|translate:'menulinks'}
                         </a>
                         <ul class="dropdown-menu">
                             {foreach $SQL.menuItemTypes as $typeID => $typeName}
                                <li>
                                   <a href="javascript:nw('menu', '0', '{$menuID}&amp;data[type]={$typeID}{if $menuID !== ''}&amp;data[id_menu]={$menuID}{/if}&amp;data[parent]={if $menuID === ''}null{else}{$menuID}{/if}');">
                                      <span class="{$SQL.menuItemTypesClasses[$typeID]}"></span> {'add'|cat:$typeName|translate:'menulinks'}
                                   </a>
                                </li>
                             {/foreach}
                         </ul>
                      </div>
                   </div>
                </div>
             </div>
             <form action="" method="post">
                 {function printTree}
                     {foreach $data as $entry}
                        <li class="node {$view->resolveCallable($tableDef.class, $entry)}" data-node-id="{$view->getListRowValue($entry, $tableDef.id)}">
                           <div class="nodeWrapper tdd-row">
                               {foreach $tableDef.fields as $name => $column}
                                  <div class="list_item tdd-column tdd-column-{$column@index + 1} {$view->resolveCallable($column.class, $entry) nofilter}">
                                      {$view->printListRowItem($column, $entry)}
                                  </div>
                               {/foreach}
                           </div>
                            {if !empty($entry.submenu)}
                               <ul>
                                   {printTree data=$entry.submenu tableDef=$tableDef}
                               </ul>
                            {/if}
                        </li>
                     {/foreach}
                 {/function}

                <div class="treeDragDrop table" id="treeDragDrop_{if $menuID}{$menuID}{else}null{/if}">
                   <ul class="tdd-tree nestedSortable nestedSortableRoot">
                       {printTree data=$menu['submenu'] tableDef=$columns}
                   </ul>
                </div>
             </form>
          </div>
       {/foreach}
   </div>
{/block}

{block js append}
   <script src="./static/js/jquery.mjs.nestedSortable.js"></script>
{/block}

<script type="text/javascript">
    {block onready append}
    $('.nestedSortableRoot').on('click', '.opener', function(event) {
       event.preventDefault();
       $(this).closest('li').toggleClass('mjs-nestedSortable-collapsed').toggleClass('mjs-nestedSortable-expanded');
       $(this).toggleClass('bi-plus-circle').toggleClass('bi-dash-circle');
       return false;
    });
    var sortableContainers = [];
    {foreach $SQL.menu as $menuID => $menu}
    {*initListTree("sections", "{$ctrl.currUrl.Rel nofilter}&acn=drag&id_menu={$id_menu}", '#treeDragDrop_{$id_menu}');*}
    var nodesContainer = $('#treeDragDrop_{if $menuID}{$menuID}{else}null{/if} > ul');
    sortableContainers.push(nodesContainer);
    nodesContainer.nestedSortable({
       handle: '.drag-drop-mover',
       items: 'li.node',
       listType: 'ul',
       toleranceElement: '> div.nodeWrapper',
       placeholder: 'placeholder',
       isTree: true,
       connectWith: '.nestedSortableRoot',
       start: function(event, ui) {
          ui.item.startPos = ui.item.index();
          var $parent = ui.item.parents('[data-node-id]');
          ui.item.startParent = $parent.length ? $parent.data('node-id') : null;
       },
       update: function(event, ui) {
          // fire only once when moving between multiple nestedSortables (use the update method of the target)
          // https://stackoverflow.com/a/7340208
          if (this !== ui.item.closest('.nestedSortableRoot')[0]) {
             return;
          }
          $.each(sortableContainers, function(index, sortable) {
             sortable.nestedSortable('disable');
          });

          // fix collapse toggle
          $('.nestedSortableRoot .node').each(function(index, el) {
             var $node = $(el);
             var $nodeToggle = $node.find('> .nodeWrapper > .nodeToggle');
             if ($node.find('> ul > .node').length) {
                $nodeToggle.fadeIn();
             } else {
                $nodeToggle.fadeOut();
             }
             if ($node.is('.mjs-nestedSortable-expanded')) {
                $nodeToggle.find('> span').addClass('glyphicon-minus-sign').removeClass('glyphicon-plus-sign');
             }
          });

          var $parent = ui.item.parents('[data-node-id]');
          var data = {ldelim}tree: {ldelim}{rdelim}{rdelim};
          data['tree']['id'] = ui.item.data('node-id');
          if ($parent.length) {
             data['tree']['target'] = $parent.data('node-id');
          }
          data['tree']['position'] = ui.item.index();

          // up or down?
          if (ui.item.startParent === data['tree']['target'] && ui.item.startPos <= data['tree']['position']) {
             data['tree']['position'] += 1;
          }

          $.post('{$ctrl.currUrl.Rel nofilter}&acn=drag&menuID={if $menuID}{$menuID}{else}null{/if}', data, function(res) {
             //console.log (res.data.msg);
             //TODO: error handling
             return true;
          });

          $.each(sortableContainers, function(index, sortable) {
             sortable.nestedSortable('enable');
          });
       },
    });
    {/foreach}
    {/block}
</script>

{block unsortable}unsortable{/block}

{block bottomPagination}
{/block}
