// Date: 09.06.2021
// Reordering side menu

var tableData;
var editedMenu;
var gridId = $("#side-menu.sortable-menu").data("grid-id");
var isTabletOrMobile = false;
var wasMenuScrolled = false;

$(function () {
    isTabletOrMobile = paw.utils.dom.isTabletOrMobileWidth(); // equals $max-screen-sm css breakpoint
    resizeMenu();

    touchScrollSortList($('#main-menu-navbar'), $('#side-menu'));

    $('#mobile-menu-settings-table').mobileMenuSettings({
        mainMenuSelector: '#main-menu-navbar #side-menu',
        mainMenuItemSelector: '> li:not(.nav-header) > a',
        modalSelector: '#mobile-menu-instances',
        preloaderSelector: '#mobile-menu-instances #mobile-menu-instances-preloader'
    });
});

var mainMenuConfig = (function (paw, utils) {
    function MainMenuConfig() {

    }

    MainMenuConfig.prototype.fetch = function () {
        var self = this;
        var fallbackId = $('#side-menu').data('grid-id-fallback');
        // fetch menu configuration or fallback to default configuration when menu configuration is empty
        return this.fetchConfig(gridId).then(function (res) {
            if (!utils.value.isSet(res) || !utils.value.isSet(res.Columns)) {
                return self.fetchConfig(fallbackId);
            }
            return res;
        });
    };

    MainMenuConfig.prototype.fetchConfig = function (tableName) {
        return utils.async.get({
            url: $("#GetTableGrid").val(),
            params: {
                TableName: tableName
            }
        }).then(function (data) {
            if (!jQuery.isEmptyObject(data)) {
                tableData = data;
            }
            return data;
        });
    };

    return new MainMenuConfig();
})(paw, paw.utils);

let menuResizeTimer;
$(window).on('resize', function () {
    isTabletOrMobile = paw.utils.dom.isTabletOrMobileWidth(); // equals $max-screen-sm css breakpoint
    clearTimeout(menuResizeTimer);
    menuResizeTimer = setTimeout(resizeMenu, 200);
});

$(document).ready(function () {
    loadMenuConfig().then(function () {
        reorderMenu();
        setMobileMenu(tableData);
    });
});

function loadMenuConfig() {
    return mainMenuConfig.fetch();
}

function saveMenuConfig($list) {
    

    let columns = [];
    let column = {};
    var mms = $('#mobile-menu-settings-table').mobileMenuSettings();
    mms.preloader(true);
    if (paw.utils.value.notSet($list)) {
        $list = $("#side-menu.sortable-menu");
    }

    $list.children().each(function (i) {
        var listId = $(this).data("list-item-id");
        var position = $list.find('li[data-list-item-id="' + listId + '"]').index();

        var item = mms.getItem(listId);
        var isHidden = paw.utils.value.isSet(item) && !item.isChecked;

        column = {
            Id: listId,
            Position: position,
            IsHidden: false
        };

        if (isTabletOrMobile) {
            column.IsHidden = isHidden;
        } else if (paw.utils.value.isSet(tableData)) {
            var tcol = tableData.Columns.filter(col => col.Id === listId)[0];
            column.IsHidden = paw.utils.value.notSet(tcol) || tcol.IsHidden;
        }

        columns.push(column);
    });

    var data = {
        TableName: gridId,
        Columns: columns
    }

    var d = paw.utils.async.defer();
    $.ajax({
        url: $("#SaveTableGrid").val(),
        method: 'POST',
        data: data,
        success: function () {
            if (isTabletOrMobile) {
                setMobileMenu(data);
                tableData = data;
            }
            $('#mobile-menu-instances').modal('hide');
            mms.preloader(false);
            d.resolve();
        },
        error: function () {
            mms.preloader(false);
            d.reject();
        }
    });
    return d.promise;
}

function resizeMenu() {
    if (isTabletOrMobile) {
        setMobileMenu(tableData);
    }
    else {
        setDesktopMenu(tableData);
    }

    if ($("#side-menu.sortable-menu").hasClass("ui-sortable")) return;

    // TODO: uncomment when sorting is unified with angular menu
    //$("#side-menu.sortable-menu").sortable({
    //    cursor: "move",
    //    placeholder: "ui-state-highlight",
    //    opacity: 0.7,
    //    helper: "clone",
    //    items: "li:not([data-sortable])",
    //    start: function (e, ui) {
    //        ui.item.addClass('menu-item-issorting');
    //        ui.helper.addClass('menu-sort-item-clone');
    //    },
    //    stop: function (e, ui) {
    //        setTimeout(function () {
    //            ui.item.removeClass('menu-item-issorting');
    //        }, 100);

    //        if (wasMenuScrolled) {
    //            wasMenuScrolled = false;
    //            return false;
    //        }
    //        else {
    //            saveMenuConfig();
    //            $.mobileMenu().reorder();
    //        }
            
    //    }
    //}).disableSelection();

    
}

function reorderMenu() {
    // TODO: uncomment when sorting is unified with angular menu
    //if (!tableData) return;

    //var rowOrder = {};
    //var ul = $("#side-menu.sortable-menu");
    //var li = ul.children();

    //$("#side-menu.sortable-menu").children().each(function (i) {
    //    var listId = $(this).data("list-item-id");
    //    var columnData = tableData.Columns.filter(el => { return el.Id === listId })[0];
    //    if (columnData) {
    //        rowOrder[i] = columnData.Position;
    //    }
    //});

    //li.sort(function (a, b) {
    //    return rowOrder[$(a).index()] - rowOrder[$(b).index()];
    //});

    //ul.append(li);
    //$.mobileMenu().reorder();
}

// Mobile menu
function setMobileMenu(data) {
    if (!isTabletOrMobile || !tableData) return;

    var mms = $('#mobile-menu-settings-table').mobileMenuSettings();

    // Skip first element because it is logo
    // TODO: uncomment when sorting is unified with angular menu
    //data.Columns.slice(0).map((col) => {
    //    if (col.IsHidden) {
    //        // Hide in menu 
    //        $("li[data-list-item-id='" + col.Id + "']").addClass("hidden-column");
    //    } else {
    //        $("li[data-list-item-id='" + col.Id + "']").removeClass("hidden-column");
    //    }
    //    mms.setItemEnabled(col.Id, !col.IsHidden);
    //});
    $.mobileMenu().menuBar.fitBarItems();
} 

function setDesktopMenu(data) {
    if (isTabletOrMobile || !tableData) return;

    // show all menu items on desktop
    $("#main-menu-navbar li[data-list-item-id]").removeClass("hidden-column");
} 


function touchScrollSortList($container, $list) {
    var isScrolling = false;
    var preventScroll = false;
    var pressTimer;
    
    var startY = 0;
    var mobilePressDelay = 1000;
    var startTime = 0;

    // listen for list item touch events
    $list.find('li').on("touchstart", function (e) {
        if (!isTabletOrMobile) {
            return;
        }

        startTime = new Date().getTime();
        preventScroll = false;

        var $item = $(this);
        $item.addClass("menu-item-touched");
        
        // after press delay has passed, prevent scroll and allow sorting
        pressTimer = setTimeout(function () {
            preventScroll = true;
            $item.addClass("menu-sort-item-selected");
            wasMenuScrolled = false;
        }, mobilePressDelay);
    }).on('touchnmove', function (e) {
        if (!isTabletOrMobile) {
            return;
        }

        if (!preventScroll) {
            clearTimeout(pressTimer);
        }
    }).on('touchend', function (e) {
        if (!isTabletOrMobile) {
            return;
        }
        clearTimeout(pressTimer);
        preventScroll = true;
    });

    // listen for container's (scrollable holder) touch events
    $container.on("touchstart", function (event) {
        if (!isTabletOrMobile) {
            return;
        }

        startY = event.originalEvent.touches[0].clientY;
        isScrolling = false;
        preventScroll = false;
    }).on("touchmove", function (event) {
        if (!isTabletOrMobile) {
            return;
        }

        var now = new Date().getTime();
        var elapsed = now - startTime > mobilePressDelay;
        var deltaY = event.originalEvent.touches[0].clientY - startY;

        // scroll prevented or press delay has elapsed
        if (preventScroll || (elapsed && preventScroll) || deltaY === 0) {
            isScrolling = false;
            wasMenuScrolled = false;
            return;
        }

        // activate scroll and cancel sorting
        wasMenuScrolled = true;
        isScrolling = true;
        preventScroll = false;
        

        $list.trigger('cancel');
        clearTimeout(pressTimer);

        // dirty solution for hiding sort element - sort is activated on initial drag
        $list.find('.menu-item-touched').css('display', 'block');
        $list.find('li.menu-sort-item-clone').css({
            display: 'none'
        });
        $list.find('li.ui-sortable-placeholder').css('display', 'none');        

        // update container scroll as it is blocked (event propagation) by sortable list elements
        $container.scrollTop($container.scrollTop() - deltaY);
        startY = event.originalEvent.touches[0].clientY;
    }).on("touchend", function (event) {
        if (!isTabletOrMobile) {
            return;
        }

        if (isScrolling) {
            preventScroll = true;
            isScrolling = false;
        }
        $list.find('.menu-item-touched').css('display', '').removeClass('menu-item-touched menu-sort-item-selected');
        clearTimeout(pressTimer);
    });
}