{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 js append}
   <script src="./static/js/jquery.mjs.nestedSortable.js"></script>
{/block}

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

{block 'list-filter'}
   <div class="wpj-panel-heading">
      <div class="list-filters-wrapper">
         <div class="list-filters-left">
             <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>
         </div>
         <div class="list-filters-right">
            <div class="filter-item">
               <button title="Upravit zobrazení sloupců" onclick="nw('ListColumns', '', 'pg={$smarty.get.type}')"
                       class="btn btn-xs btn-ghost">
                  <i class="bi bi-arrows-move m-r-1"></i>{'editListColumns'|translate:'filters'}
               </button>
            </div>
         </div>
      </div>
   </div>
{/block}

{block listTable}
    {block 'sections-header'}
       <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>
    {/block}

    <div class="table">
        {include "./sections.ajax.tpl"}
    </div>
{/block}

{block bottomPagination}
   <div class="pagination-sticky">
      <div class="pagination-buttons">
          {if findModule('products_sections', 'virtual_to_db')}
             <div class="filter-item">
                <a href="launch.php?s=list.php&type={$view->getListName()}&acn=generateVirtualSections"
                   class="btn btn-danger"
                   title="Přegeneruje virtuální sekce, které se jinak přegeneovávájí jednou za dvě hodiny.">
                   Přegenerovat virtuální sekce
                </a>
             </div>
          {/if}
          {block "list-filter-mass-edit"}
              {if $showMassEdit}
                 <a title="Hromadná úprava" href="launch.php?s=listEdit.php&type={$view->getListName()}"
                    class="btn btn-secondary"><span class="bi bi-list-check m-r-1"></span>Hromadná úprava
                 </a>
              {/if}
          {/block}
      </div>
   </div>
{/block}

{block unsortable}unsortable{/block}

<script>
   {block onready append}

   function setCookie(c_name, value, exdays) {
      var exdate = new Date();
      exdate.setDate(exdate.getDate() + exdays);
      var c_value = encodeURIComponent(value) + '; path=/' + (exdays == null ? '' : '; expires=' + exdate.toUTCString());
      document.cookie = c_name + '=' + c_value;
   }

   const getOpened = () => $.map($('.treeDragDrop').find('li .opener:not(.plus)'), function(elem) {
      return $(elem).closest("li").data("id");
   });

   function customRefresh(url) {
      const openedBranches = getOpened();
      if (openedBranches.length) {
         setCookie('products_list_opened_sections', JSON.stringify(openedBranches))
      }

      setWindowStorage("listPosition_x", window.scrollY, window);

      var js = $('.highRow').find("td a[href^=javascript]").attr('href');
      var ID;
      if (typeof js == 'undefined')
         ID = 0;
      else
         ID = js.replace(/javascript:nw\(\'(.+)'\, '(\d+)'\, '(.*)'\);/, '$2');

      setWindowStorage("listHighRow", ID, window);
   }


   {literal}
   function initListTreeAjax(name, url, selector) {
      var $tree = $(selector ? selector : '#sectionsRoot  > ul');

      $('#sectionsRoot > ul').nestedSortable({
         handle: '.drag-drop-mover',
         items: '.node',
         listType: 'ul',
         toleranceElement: '> .nodeWrapper',
         placeholder: 'placeholder',
         isTree: true,
         connectWith: '.nestedSortableRoot',
         start: function(event, ui) {
            /* on drag start find index and parent id of moved item */
            ui.item.startPos = ui.item.index();
            var $parent = ui.item.parents('[data-id]');
            ui.item.startParent = $parent.length ? $parent.data('id') : null;
         },
         update: function(event, ui) {
            var $parent = ui.item.parents('[data-id]');
            var $prev = ui.item.prev();
            var $next = ui.item.next();

            var data = {
               tree: {
                  id: ui.item.data('id'),
                  position: ui.item.index()
               }
            };

            if ($parent.length) {
               data['tree']['target'] = $parent.data('id');
            }

            if ($prev.length) {
               data['tree']['after'] = $prev.data('id');
            }

            if ($next.length) {
               data['tree']['before'] = $next.data('id');
            }

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

            $.post(url, data, function(res) {
               //TODO: error handling
               return true;
            });
         },
      });

      $tree.on("click", "li .opener:not(.disabled)", function() {
         var $li = $(this).closest("li");
         var $this = $(this);
         var $ul = $li.children("ul").first();
         var id = $li.data("id");

         const toggleOpen = () => {
            $this.removeClass("plus").addClass('minus');
            $li.removeClass('mjs-nestedSortable-collapsed').addClass('mjs-nestedSortable-expanded');
         }

         const toggleClosed = () => {
            $this.removeClass("minus").addClass('plus');
            $li.addClass('mjs-nestedSortable-collapsed').removeClass('mjs-nestedSortable-expanded');
         }

         if (!$this.is(".plus")) {
            toggleClosed();
         } else {
            if ($ul.length < 1) {
               $.ajax({
                  url: window.location,
                  type: "get",
                  data: {
                     root: id
                  },
                  success: function(response) {
                     $li.append($(response).html());
                     toggleOpen();
                      {/literal}
                      {block subsectionLoaded}

                      {/block}
                      {literal}
                  },
                  error: function() {
                     showInfoMessage('Chyba při načítání podsekcí', 'danger');
                  }
               });
            } else {
               toggleOpen();
            }
         }

         return false;
      });
      return this;
   }
   {/literal}

   initListTreeAjax("sections", "{$ctrl.currUrl.Rel nofilter}&acn=drag");

   {/block}
</script>

