<div class="p20">
    <div id="loading-indicator" class="hide">
        <div class="display-flex align-items-center justify-content-center">
            <img src="[{$dir_images}]axialis/user-interface/loading.svg" class="animation-rotate mr5" alt="" />
            <span>[{isys type="lang" ident="LC__UNIVERSAL__LOADING"}]</span>
        </div>
    </div>

    <div class="mb20 display-flex">
        [{isys type="f_dialog" p_strClass="input-small" name="C__CATEGORY_FOLDERS__OBJECT_TYPE" chosen=true p_bInfoIconSpacer=0}]

        [{isys name="C__CATEGORY_FOLDERS__REORDER_POPUP" type="f_popup"}]
        [{isys name="C__CATEGORY_FOLDERS__CREATE_FOLDER_POPUP" type="f_popup"}]
        [{isys name="C__CATEGORY_FOLDERS__RESET_POPUP" type="f_popup"}]
    </div>

    <p id="category-folders-description" class="display-flex align-items-center">
        <img src="[{$dir_images}]axialis/basic/button-help.svg" alt="" class="mr5" /><span>[{isys type="lang" ident="LC__CATEGORY_FOLDERS__DESCRIPTION"}]</span>
    </p>

    <div class="pt20 mb15 display-flex align-items-center">
        <button id="toggle-all" type="button" class="btn btn-secondary hide" 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">
            <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>

    <div id="category-tree" class="category-folders-config hide">
        <!-- To be filled by JS -->
    </div>

    <input type="hidden" id="configuration" name="configuration" value="" />
</div>

<style>
    [{include file=$cssPath}]
</style>

<script>
    idoit.Translate.set('LC__CATEGORY_FOLDERS__FOLDER_EMPTY', '[{isys type="lang" ident="LC__CATEGORY_FOLDERS__FOLDER_EMPTY"}]');
    idoit.Translate.set('LC__CATEGORY_FOLDERS__EXPAND_ALL', '[{isys type="lang" ident="LC__CATEGORY_FOLDERS__EXPAND_ALL"}]');
    idoit.Translate.set('LC__CATEGORY_FOLDERS__COLLAPSE_ALL', '[{isys type="lang" ident="LC__CATEGORY_FOLDERS__COLLAPSE_ALL"}]');
    idoit.Translate.set('LC__CATEGORY_FOLDERS__DELETE_FOLDER', '[{isys type="lang" ident="LC__CATEGORY_FOLDERS__DELETE_FOLDER"}]');
    idoit.Translate.set('LC__CATEGORY_FOLDERS__MOVE_CATEGORY', '[{isys type="lang" ident="LC__CATEGORY_FOLDERS__MOVE_CATEGORY"}]');
    idoit.Translate.set('LC__CATEGORY_FOLDERS__MOVE_FOLDER', '[{isys type="lang" ident="LC__CATEGORY_FOLDERS__MOVE_FOLDER"}]');
    idoit.Translate.set('LC__CATEGORY_FOLDERS__ADD_FOLDER', '[{isys type="lang" ident="LC__CATEGORY_FOLDERS__ADD_FOLDER"}]');
    idoit.Translate.set('LC__CATEGORY_FOLDERS__EDIT_FOLDER', '[{isys type="lang" ident="LC__CATEGORY_FOLDERS__EDIT_FOLDER"}]');
    idoit.Translate.set('LC__CATEGORY_FOLDERS__NO_SEARCH_RESULTS', '[{isys type="lang" ident="LC__CATEGORY_FOLDERS__NO_SEARCH_RESULTS"}]');

    const $objectTypeSelection = $('C__CATEGORY_FOLDERS__OBJECT_TYPE');
    const $categoryTree = $('category-tree');
    const $loadingIndicator = $('loading-indicator');
    const $toggleAllButton = $('toggle-all');
    const $searchCategoryField = $('scroller').down('.category-folders-search-container');
    const $configurationField = $('configuration');
    const $reorderButton = $('C__CATEGORY_FOLDERS__REORDER_POPUP');
    const $addFolderButton = $('C__CATEGORY_FOLDERS__CREATE_FOLDER_POPUP');
    const $resetButton = $('C__CATEGORY_FOLDERS__RESET_POPUP');
    const canEdit = JSON.parse('[{$canEdit|json_encode|escape:"javascript"}]');

    idoit.Require
        .addModule('pro.category-folders-tree', '[{$proWwwDir}]assets/js/category-folders/tree.js')
        .require('pro.category-folders-tree', function () {
            const tree = new CategoryFoldersTree($categoryTree, {
                addable:              canEdit,
                editable:             canEdit,
                movable:              canEdit,
                deletable:            canEdit,
                $toggleAll:           $toggleAllButton,
                $searchCategoryField: $searchCategoryField,
            });

            const reloadAndRender = (objectTypeId, hideTree) => {
                if (objectTypeId <= 0) {
                    idoit.Notify.info('[{isys type="lang" ident="LC__CATEGORY_FOLDERS__SELECT_OBJECT_TYPE"}]');
                    return;
                }

                $loadingIndicator.removeClassName('hide');

                if (hideTree) {
                    $categoryTree.addClassName('hide');
                }

                new Ajax.Request('[{$loadConfigUrl}]' + objectTypeId, {
                    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;
                        }

                        $categoryTree.update();

                        tree.setData(json.data.categories);
                        tree.setConfigurationId(json.data.configId);
                        tree.setObjectTypeId(objectTypeId);

                        // @see ID-9763 Let it render, so we'll get the correct ordering.
                        tree.render();

                        if (json.data.configId === 0 && canEdit) {
                            createConfigurationOfCurrentState(objectTypeId);
                            return;
                        }

                        // Hide the loading and show the category tree.
                        $loadingIndicator.addClassName('hide');
                        $categoryTree.removeClassName('hide');

                        if (canEdit) {
                            $reorderButton.removeClassName('disabled').enable();
                            $addFolderButton.removeClassName('disabled').enable();
                            $resetButton.removeClassName('disabled').enable();
                        }

                        $configurationField.setValue(JSON.stringify({
                            configId:     json.data.configId,
                            objectTypeId: objectTypeId
                        }));
                    }
                });
            };

            $objectTypeSelection.on('change', () => {
                if ($('category-folders-description')) {
                    $('category-folders-description').remove();
                }
                reloadAndRender($objectTypeSelection.getValue(), true);
            });

            $categoryTree.on('reload:structure', () => {
                reloadAndRender($objectTypeSelection.getValue(), false);
            });

            // This is how the save call needs to look.
            const createConfigurationOfCurrentState = (objectTypeId) => {
                const structureData = tree.getData();

                new Ajax.Request('[{$saveConfigUrl}]' + objectTypeId, {
                    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;
                        }

                        reloadAndRender(objectTypeId);
                    }
                });
            }
        });
</script>
