[{isys_group name="tom.popup.category-folders.move-item"}]
<div id="category-folders-popup_reorder-item">
    <div class="modal-header">
        <h1>[{isys type="lang" ident="LC__CATEGORY_FOLDERS__POPUP__REORDER_ELEMENT__TITLE"}]</h1>
        <button type="button" class="btn btn-secondary popup-closer ml-auto" title="[{isys type="lang" ident="LC__POPUP__CLOSE"}]" data-tooltip="1">
            <img class="fr mouse-pointer" alt="" src="[{$dir_images}]axialis/user-interface/window-control-close.svg" />
        </button>
    </div>

    <div class="modal-content p20">
        <p>[{isys type="lang" ident="LC__CATEGORY_FOLDERS__POPUP__REORDER_ELEMENT__DESCRIPTION"}]</p>

        <div class="mb15 display-flex align-items-center mt10 mb15">
            <button type="button" class="btn btn-secondary" data-function="toggle-all" data-action="expand">
                <img src="[{$dir_images}]axialis/user-interface/angle-right-small.svg" alt="" /><span>[{isys type="lang" ident="LC__CATEGORY_FOLDERS__EXPAND_ALL"}]</span>
            </button>

            <div class="category-folders-search-container hide mr20">
                <input type="text" class="input input-small" placeholder="[{isys type="lang" ident="LC__UNIVERSAL__SEARCH"}]" />
                <img src="[{$dir_images}]axialis/basic/zoom.svg" alt="" />
            </div>

            <div>
                <button type="button" class="btn move-button" disabled>
                    <img src="[{$dir_images}]axialis/documents-folders/folder-copy-2-grey.svg" alt="" /><span>[{isys type="lang" ident="LC__CATEGORY_FOLDERS__POPUP__SELECT_FOLDER__MOVE"}]</span>
                </button>
            </div>
        </div>

        <div class="category-folders-config">
            <!-- Will be filled by JS -->
        </div>

        <div id="category-folders-popup_reorder-item-memo"></div>
    </div>

    <div class="modal-footer">
        <button type="button" class="btn save-button mr5">
            <img src="[{$dir_images}]axialis/basic/symbol-ok.svg" alt="" /><span>[{isys type="lang" ident="LC__UNIVERSAL__BUTTON_SAVE"}]</span>
        </button>
        <button type="button" class="btn popup-closer">
            <img src="[{$dir_images}]axialis/basic/symbol-cancel.svg" alt="" /><span>[{isys type="lang" ident="LC__UNIVERSAL__BUTTON_CANCEL"}]</span>
        </button>
    </div>
</div>

<script type="text/javascript">
    (function () {
        "use strict";

        Position.includeScrollOffsets = true;

        // #category-tree is the "main" tree and will be used for callbacks.
        const $categoryTree = $('category-tree');

        const $popup = $('category-folders-popup_reorder-item');
        const $saveButton = $popup.down('.save-button');
        const $treeContainer = $popup.down('.category-folders-config');
        const $toggleAllButton = $popup.down('[data-function="toggle-all"]');
        const $searchCategoryField = $popup.down('.category-folders-search-container');
        const $moveButton = $popup.down('.move-button');
        // A helper element to receive memo data.
        const $memoField = $('category-folders-popup_reorder-item-memo');

        let configurationId = 0;

        idoit.Translate.set('LC__CATEGORY_FOLDERS__PLACE_N_HERE', '[{isys type="lang" ident="LC__CATEGORY_FOLDERS__PLACE_N_HERE"}]');

        idoit.Require
            .addModule('pro.category-folders-dnd-tree', '[{$proWwwDir}]assets/js/category-folders/dnd-tree.js')
            .require('pro.category-folders-dnd-tree', function () {
                const tree = new CategoryFoldersDnDTree($treeContainer, {
                    $toggleAll: $toggleAllButton,
                    $searchCategoryField: $searchCategoryField,
                    $scrollContainer: $popup.down('.modal-content'),
                    onSelect:         function () {
                        if (tree.getSelection().length === 0) {
                            $moveButton.disable();
                            return;
                        }

                        $moveButton.enable();
                    },
                    afterRender:      function () {
                        tree.prepareDraggables();
                        tree.prepareDroppables();
                    }
                });

                new Ajax.Request('[{$loadConfigUrl}]', {
                    method:     'get',
                    onComplete:  function (xhr) {
                        if (!is_json_response(xhr, true)) {
                            return;
                        }

                        const json = xhr.responseJSON;

                        if (!json.success) {
                            idoit.Notify.error(json.message, { sticky: true });
                            return;
                        }

                        configurationId = json.data.configId;

                        tree.setData(json.data.categories);
                        tree.render();
                    }
                });

                $moveButton.on('click', function () {
                    const selection = tree.getSelection();

                    if (selection.length === 0) {
                        return;
                    }

                    // @see ID-10004 Check for a singular parent.
                    const parentId = selection.length === 1
                        ? (selection[0].up('.folder-container[data-id]')
                            ? selection[0].up('.folder-container[data-id]').readAttribute('data-id')
                            : null)
                        : null;

                    Modal.openLegacy({
                        popupType:  'category_folders_move',
                        maxWidth:   720,
                        maxHeight:  600,
                        parameters: {
                            static: {
                                configurationId: configurationId,
                                returnAsMemo: 'category-folders-popup_reorder-item-memo',
                                objectTypeId: +'[{$objectTypeId}]',
                                items:        selection.map(($item) => parseInt($item.readAttribute('data-id'))),
                                parentId:     parentId
                            }
                        }
                    });
                });

                $memoField.on('update:position', function (ev) {
                    const selection = tree.getSelection();
                    const $newParent = ev.memo.isRoot
                        ? $popup.down('.category-folders-config')
                        : $popup.down('[data-id="' + ev.memo.selectedParent + '"] .folder-children-container');

                    if (!$newParent) {
                        idoit.Notify.info('[{isys type="lang" ident="LC__CATEGORY_FOLDERS__MOVE_ITEMS_ERROR"}]');
                        return
                    }

                    for (let i in selection) {
                        if (! selection.hasOwnProperty(i)) {
                            continue;
                        }

                        const $oldParent = selection[i].up('.folder-children-container');

                        $newParent.insert({ top: selection[i] });

                        // @see ID-10069 Check if the old parent is now empty.
                        if ($oldParent && $oldParent.select('.category,.folder-container').length === 0) {
                            $oldParent.insert(tree.$emptyFolderHtml);
                        }
                    }

                    // @see ID-10069 Check if the new parent has a 'left over' empty indicator.
                    if ($newParent.down('>p')) {
                        $newParent.down('>p').remove();
                    }

                    tree.rebuildData();
                    tree.render();
                    // @see ID-10087 Re-trigger the search, in case the list was previously in search context.
                    tree.categorySearch();
                });

                $popup.on('click', '.popup-closer', function () {
                    Modal.close($popup.up('.modal'));
                });

                $saveButton.on('click', function () {
                    const structureData = tree.getData();

                    new Ajax.Request('[{$saveConfigUrl}]', {
                        method:     'post',
                        parameters: {
                            folders:    JSON.stringify(structureData.folders),
                            categories: JSON.stringify(structureData.categories)
                        },
                        onComplete:  function (xhr) {
                            if (!is_json_response(xhr, true)) {
                                return;
                            }

                            const json = xhr.responseJSON;

                            if (!json.success) {
                                idoit.Notify.error(json.message, { sticky: true });
                                return;
                            }

                            $categoryTree.fire('reload:structure');
                            Modal.close($popup.up('.modal'));
                        }
                    });
                });
            });
    })();
</script>
[{/isys_group}]
