<?php /** @var \Solwin\Verticalmenu\Block\Adminhtml\Menu\Tree $block */ ?>
<div class="categories-side-col">
    <div class="sidebar-actions">
        <?php if ($block->getRoot()): ?>
            <?php echo $block->getAddRootButtonHtml() ?><br/>
            <?php echo $block->getAddSubButtonHtml() ?>
        <?php endif; ?>
    </div>
    <div class="tree-actions">
        <?php if ($block->getRoot()): ?>
            <a href="#" onclick="tree.collapseTree();
                        return false;">
                   <?php echo __('Collapse All'); ?>
            </a>
            <span class="separator">|</span>
            <a href="#" onclick="tree.expandTree();
                        return false;">
                   <?php echo __('Expand All'); ?>
            </a>
        <?php endif; ?>
    </div>
    <?php if ($block->getRoot()): ?>
        <div class="tree-holder">
            <div id="tree-div" class="tree-wrapper"></div>
        </div>
    </div>

    <div data-id="information-dialog-menu" class="messages" style="display: none;">
        <div class="message message-notice">
            <div><?php echo __('This operation can take a long time'); ?></div>
        </div>
    </div>
    <script id="ie-deferred-loader" defer="defer" src=""></script>
    <script>
                var tree;
                require([
                    "jquery",
                    'Magento_Ui/js/modal/modal',
                    "jquery/ui",
                    "prototype",
                    "extjs/ext-tree-checkbox",
                    "mage/adminhtml/form",
                    "mage/translate"
                ], function (jQuery) {

                    /**
                     * Fix ext compatibility with prototype 1.6
                     */
                    Ext.lib.Event.getTarget = function (e) {
                        var ee = e.browserEvent || e;
                        return ee.target ? Event.element(ee) : null;
                    };

                    Ext.tree.TreePanel.Enhanced = function (el, config) {
                        Ext.tree.TreePanel.Enhanced.superclass.constructor.call(this, el, config);
                    };

                    Ext.extend(Ext.tree.TreePanel.Enhanced, Ext.tree.TreePanel, {
                        loadTree: function (config, firstLoad) {
                            var parameters = config['parameters'];
                            var data = config['data'];

                            if ((typeof parameters['root_visible']) != 'undefined') {
                                this.rootVisible = parameters['root_visible'] * 1;
                            }

                            var root = new Ext.tree.TreeNode(parameters);

                            this.nodeHash = {};
                            this.setRootNode(root);

                            if (firstLoad) {
                                this.addListener('click', this.menuClick);
                                this.addListener('beforenodedrop', menuMove.createDelegate(this));
                            }

                            this.loader.buildMenuTree(root, data);
                            this.el.dom.innerHTML = '';
                            // render the tree
                            this.render();
                            if (parameters['expanded']) {
                                this.expandAll();
                            } else {
                                root.expand();
                            }

                            var selectedNode = this.getNodeById(parameters['menu_id']);
                            if (selectedNode) {
                                this.currentNodeId = parameters['menu_id'];
                            }

                            this.getNodeById(parameters['menu_id']).select(selectedNode);
                            this.selectCurrentNode();

                            // Temporary solution will be replaced after refactoring of tree functionality
                            jQuery('body').off('tabsactivate.tree').on('tabsactivate.tree', jQuery.proxy(function (e, ui) {
                                this.activeTab = jQuery(ui.newTab).find('a').prop('id');
                            }, this))
                        },
                        request: function (url, params) {
                            if (!params) {
                                if (this.activeTab) {
                                    var params = {active_tab_id: this.activeTab};
                                }
                                else {
                                    var params = {};
                                }
                            }
                            if (!params.form_key) {
                                params.form_key = FORM_KEY;
                            }
                            var result = new Ajax.Request(
                                    url + (url.match(new RegExp('\\?')) ? '&isAjax=true' : '?isAjax=true'),
                                    {
                                        parameters: params,
                                        method: 'post'
                                    }
                            );

                            return result;
                        },
                        selectCurrentNode: function () {
                            if (this.currentNodeId) {
                                var selectedNode = this.getNodeById(this.currentNodeId);
                                if ((typeof selectedNode.attributes.path) != 'undefined') {
                                    var path = selectedNode.attributes.path;
                                    this.selectPath(path);
                                } else {
                                    this.getSelectionModel().select(selectedNode);
                                }
                            }
                        },
                        collapseTree: function () {
                            this.collapseAll();

                            this.selectCurrentNode();

                            if (!this.collapsed) {
                                this.collapsed = true;
                                this.loader.dataUrl = '<?php echo $block->getLoadTreeUrl(false) ?>';
                                this.request(this.loader.dataUrl, false);
                            }
                        },
                        expandTree: function () {
                            this.expandAll();
                            if (this.collapsed) {
                                this.collapsed = false;
                                this.loader.dataUrl = '<?php echo $block->getLoadTreeUrl(true) ?>';
                                this.request(this.loader.dataUrl, false);
                            }
                        },
                        menuClick: function (node, e) {
                            var url = this.buildUrl(node.id);

                            this.currentNodeId = node.id;
                            if (!this.useAjax) {
                                setLocation(url);
                                return;
                            }
                            if (this.activeTab) {
                                var params = {active_tab_id: this.activeTab};
                            }
                            updateContent(url, params);
                        },
                        buildUrl: function (id) {
                            var urlExt = 'menu_id/' + id + '/';

                            return parseSidUrl(this.baseUrl, urlExt);
                        },
                        getBaseUrl: function () {
                            return this.baseUrl;
                        }
                    });

                    function reRenderTree(switcherParams) {
                        if (tree && switcherParams) {
                            var url;
                            if (switcherParams.useConfirm) {
                                if (!confirm("<?php echo __('Please confirm site switching. All data that hasn\'t been saved will be lost.') ?>")) {
                                    return false;
                                }
                            }

                            if ($('add_root_menu_button')) {
                                if (!switcherParams.scopeId) {
                                    $('add_root_menu_button').show();
                                }
                                else {
                                    $('add_root_menu_button').hide();
                                }
                            }

                            if (tree.useAjax) {
                                // retain current selected Menu id
                                url = tree.switchTreeUrl + switcherParams.scopeParams + 'menu_id/' + tree.currentNodeId + '/';
                                // load from cache
                                // load from ajax
                                // add form key
                                var params = {
                                    form_key: FORM_KEY
                                };
                                new Ajax.Request(url + (url.match(new RegExp('\\?')) ? '&isAjax=true' : '?isAjax=true'), {
                                    parameters: params,
                                    method: 'post',
                                    onComplete: function (transport) {
                                        var response = eval('(' + transport.responseText + ')');
                                        if (!response['parameters']) {
                                            return false;
                                        }

                                        _renderNewTree(response, switcherParams.scopeParams);
                                    }
                                });
                            } else {
                                var baseUrl = '<?php echo $block->getEditUrl() ?>';
                                var urlExt = switcherParams.scopeParams + 'menu_id/' + tree.currentNodeId + '/';
                                url = parseSidUrl(baseUrl, urlExt);
                                setLocation(url);
                            }
                        }
                        // render default tree
                        else {
                            _renderNewTree();
                        }
                    }

                    function _renderNewTree(config, scopeParams) {
                        if (!config) {
                            var config = defaultLoadTreeParams;
                        }
                        if (tree) {
                            tree.purgeListeners();
                            tree.el.dom.innerHTML = '';
                        }
                        tree = new Ext.tree.TreePanel.Enhanced('tree-div', newTreeParams);

                        tree.loadTree(config, true);

                        // try to select current Menu
                        var selectedNode = tree.getNodeById(config.parameters.menu_id);
                        if (selectedNode) {
                            tree.currentNodeId = config.parameters.menu_id;
                        }
                        tree.selectCurrentNode();

                        // update content area
                        var url = tree.editUrl;
                        if (scopeParams) {
                            url = url + scopeParams;
                        }
    <?php if ($block->isClearEdit()): ?>
                            if (selectedNode) {
                                url = url + 'menu_id/' + config.parameters.menu_id;
                            }
    <?php endif; ?>
                        //updateContent(url); //commented since ajax requests replaced with http ones to load a Menu
                    }

                    jQuery(function () {
                        menuLoader = new Ext.tree.TreeLoader({
                            dataUrl: '<?php echo $block->getLoadTreeUrl() ?>'
                        });

                        menuLoader.processResponse = function (response, parent, callback) {
                            var config = JSON.parse(response.responseText);

                            this.buildMenuTree(parent, config);

                            if (typeof callback == "function") {
                                callback(this, parent);
                            }
                        };

                        menuLoader.buildMenuTree = function (parent, config) {
                            if (!config)
                                return null;

                            if (parent && config && config.length) {
                                for (var i = 0; i < config.length; i++) {
                                    var node;
                                    var _node = Object.clone(config[i]);
                                    if (_node.children && !_node.children.length) {
                                        delete(_node.children);
                                        node = new Ext.tree.AsyncTreeNode(_node);
                                    } else {
                                        node = new Ext.tree.TreeNode(config[i]);
                                    }
                                    parent.appendChild(node);
                                    node.loader = node.getOwnerTree().loader;
                                    if (_node.children) {
                                        this.buildMenuTree(node, _node.children);
                                    }
                                }
                            }
                        };

                        menuLoader.buildHash = function (node) {
                            var hash = {};

                            hash = this.toArray(node.attributes);

                            if (node.childNodes.length > 0 || (node.loaded == false && node.loading == false)) {
                                hash['children'] = new Array;

                                for (var i = 0, len = node.childNodes.length; i < len; i++) {
                                    if (!hash['children']) {
                                        hash['children'] = new Array;
                                    }
                                    hash['children'].push(this.buildHash(node.childNodes[i]));
                                }
                            }

                            return hash;
                        };

                        menuLoader.toArray = function (attributes) {
                            var data = {form_key: FORM_KEY};
                            for (var key in attributes) {
                                var value = attributes[key];
                                data[key] = value;
                            }

                            return data;
                        };

                        menuLoader.on("beforeload", function (treeLoader, node) {
                            treeLoader.baseParams.id = node.attributes.id;
                            treeLoader.baseParams.form_key = FORM_KEY;
                        });

                        menuLoader.on("load", function (treeLoader, node, config) {
                            //varienWindowOnload();
                        });

                        scopeSwitcherHandler = reRenderTree;

                        newTreeParams = {
                            animate: false,
                            loader: menuLoader,
                            enableDD: true,
                            containerScroll: true,
                            selModel: new Ext.tree.CheckNodeMultiSelectionModel(),
                            rootVisible: '<?php echo $block->getRoot()->getIsVisible() ?>',
                            useAjax: <?php echo $block->getUseAjax() ?>,
                            switchTreeUrl: '<?php echo $block->getSwitchTreeUrl() ?>',
                            editUrl: '<?php echo $block->getEditUrl() ?>',
                            currentNodeId: <?php echo (int) $block->getMenuId() ?>,
                            baseUrl: '<?php echo $block->getEditUrl() ?>'
                        };

                        defaultLoadTreeParams = {
                            parameters: {
                                text: '<?php echo htmlentities($block->getRoot()->getName()) ?>',
                                draggable: false,
                                allowDrop: <?php if ($block->getRoot()->getIsVisible()): ?>true<?php else : ?>false<?php endif; ?>,
                                                    id: <?php echo (int) $block->getRoot()->getId() ?>,
                                                    expanded: <?php echo (int) $block->getIsWasExpanded() ?>,
                                                    menu_id: <?php echo (int) $block->getMenuId() ?>
                                                },
                                                data: <?php echo $block->getTreeJson() ?>
                                            };

                                            reRenderTree();
                                        });

                                        function addNew(url, isRoot) {
                                            if (isRoot) {
                                                tree.currentNodeId = tree.root.id;
                                            }
                                            url += 'parent/' + tree.currentNodeId;
                                            updateContent(url);
                                        }

                                        var mageDialog = (function ($) {
                                            var self = {dialogOpened: false, callback: []};

                                            self.callback = {ok: [], cancel: []};
                                            self.createDialog = function () {
                                                var onEvent = function (type, dialog) {
                                                    self.callback[type].forEach(function (call) {
                                                        call();
                                                    });
                                                    $(dialog).trigger("closeModal");
                                                    _resetState();
                                                };
                                                var _resetState = function () {
                                                    self.dialogOpened = false;
                                                    self.callback = {ok: [], cancel: []};
                                                    delete self.dialog;
                                                };
                                                self.dialog = $('[data-id="information-dialog-menu"]').modal({
                                                    title: $.mage.__('Warning message'),
                                                    buttons: [{
                                                            text: $.mage.__('Ok'),
                                                            'class': 'action-primary',
                                                            click: function () {
                                                                onEvent('ok', this);
                                                            }
                                                        }, {
                                                            text: $.mage.__('Cancel'),
                                                            'class': 'action-close',
                                                            click: function () {
                                                                onEvent('cancel', this);
                                                                _resetState();
                                                            }
                                                        }
                                                    ],
                                                    open: function () {
                                                        $(this).closest('.ui-dialog').addClass('ui-dialog-active');
                                                        self.dialogOpened = true;

                                                        var topMargin = $(this).closest('.ui-dialog').children('.ui-dialog-titlebar').outerHeight() + 30;
                                                        $(this).closest('.ui-dialog').css('margin-top', topMargin);
                                                    },
                                                    close: function (event, ui) {
                                                        $(this).trigger('closeModal');
                                                        _resetState();
                                                    }
                                                });
                                            };

                                            return {
                                                onOk: function (call) {
                                                    self.callback.ok.push(call);
                                                    return this;
                                                },
                                                onCancel: function (call) {
                                                    self.callback.cancel.push(call);
                                                    return this;
                                                },
                                                show: function () {
                                                    if (self.dialog == undefined) {
                                                        self.createDialog();
                                                    }
                                                    if (self.dialogOpened == false) {
                                                        self.dialog.trigger('openModal');
                                                    }
                                                    return this;
                                                }
                                            };
                                        })(jQuery);

                                        function menuMove(obj) {
                                            var data = {menu_id: obj.dropNode.id, form_key: FORM_KEY};

                                            data.point = obj.point;
                                            console.log(obj.point);
                                            switch (obj.point) {
                                                case 'above' :
                                                    data.pid = obj.target.parentNode.id;
                                                    data.paid = obj.dropNode.parentNode.id;
                                                    if (obj.target.previousSibling) {
                                                        data.aid = obj.target.previousSibling.id;
                                                    } else {
                                                        data.aid = 0;
                                                    }
                                                    break;
                                                case 'below' :
                                                    data.pid = obj.target.parentNode.id;
                                                    data.aid = obj.target.id;
                                                    break;
                                                case 'append' :
                                                    data.pid = obj.target.id;
                                                    data.paid = obj.dropNode.parentNode.id;
                                                    if (obj.target.lastChild) {
                                                        data.aid = obj.target.lastChild.id;
                                                    } else {
                                                        data.aid = 0;
                                                    }
                                                    break;
                                                default :
                                                    obj.cancel = true;
                                                    return obj;
                                            }

                                            var pd = [];
                                            for (var key in data) {
                                                pd.push(encodeURIComponent(key), "=", encodeURIComponent(data[key]), "&");
                                            }
                                            pd.splice(pd.length - 1, 1);

                                            mageDialog.onOk(function () {
                                                (function ($) {
                                                    $.ajax({
                                                        url: '<?php echo $block->getMoveUrl() ?>',
                                                        method: 'POST',
                                                        data: pd.join(""),
                                                        showLoader: true
                                                    }).done(function (data) {
                                                        if (data.messages && data.messages.length > 0) {
                                                            $('[name=menu-edit-form] .messages').html(data.messages);
                                                        }
                                                        if (data.error) {
                                                            reRenderTree();
                                                        } else {
                                                            $(obj.tree.container.dom).trigger('menuMove.tree');
                                                        }
                                                    }).fail(function (jqXHR, textStatus) {
                                                        if (window.console) {
                                                            console.log(textStatus);
                                                        }
                                                        location.reload();
                                                    });
                                                })(jQuery);
                                            }).onCancel(function () {
                                                reRenderTree();
                                            }).show();
                                        }
                                        window.addNew = addNew;

                                    });
    </script>
    <?php

 endif;
