// Date: 09.06.2021
// Reordering side menu

var editedMenu;
var gridId = $(".sortable-menu").data("grid-id");

$(function () {
    resizeMenu();
});

let menuResizeTimer;
$(window).on('resize', function () {
    clearTimeout(menuResizeTimer);
    menuResizeTimer = setTimeout(resizeMenu, 200);
});

function resizeMenu() {
    if ($(".sortable-menu").hasClass("ui-sortable")) return;

    $(".sortable-menu").sortable({
        cursor: "move",
        placeholder: "ui-state-highlight",
        opacity: 0.7,
        helper: "clone",
        items: "li:not([data-sortable])",
        stop: function () {
            saveMenuConfig();
        }
    });
    $(".sortable-menu").disableSelection();
}

function saveMenuConfig() {
    let columns = [];
    let column = {};

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

        column = {
            Id: listId,
            Position: position
        };
        columns.push(column);
    });

    $.ajax({
        url: $("#SaveTableGrid").val(),
        method: 'POST',
        data: {
            TableName: gridId,
            Columns: columns
        },
        success: function () {
        }
    });
}

function reorderMenu() {
    if (!tableData) return;

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

    $(".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);
}

function loadMenuConfig() {
    return $.ajax({
        url: $("#GetTableGrid").val(),
        data: {
            TableName: gridId
        },
        success: function (data) {
            if (!jQuery.isEmptyObject(data)) {
                tableData = data;
            }
        }
    });
}

$(document).ready(function () {
    loadMenuConfig().done(function () {
        reorderMenu();
    });
});