const dividedContentMainWidthPercentLocalStorrageToken = "dividedContentMainWidthPercent_" + window.location.href.split("?")[0];
const dividedContentOpenedLocalStorrageToken = "dividedContentOpened_" + window.location.href.split("?")[0];

function getdividedContentCoordinateDifferacne(percent, $container) {
    let containerWidth = $container.width();
    let baseWidthPx = containerWidth / 100 * 70;
    let offsetWidthPx = containerWidth / 100 * percent;
    return offsetWidthPx - baseWidthPx;
}

$.fn.dividedContent = function () {
    $container = this;
    let lastCoordinateDifference = 0;
    let currentSidePercent

    if (!$container.find(".divided-content-main").hasClass("divided-content-full") && $container.find(".divided-content-side") != null && $container.find(".divided-content-side").length > 0) {
        let $toggleButton = $("<div class='divided-content-toggle'></div>");
        $toggleButton.append("<div class='divided-content-toggle-close'><i class='fas fa-chevron-right'></i><span>" + $("#dividedContent-hide").val() + "</span></div>");
        $toggleButton.append("<div class='divided-content-toggle-open hidden'><i class='fas fa-chevron-left'></i><span>" + $("#dividedContent-show").val() + "</span></div>");

        $container.find(".divided-content-main").append($toggleButton);
        $container.find(".divided-content-side").append("<div class='divided-content-resizer'></div>");

        currentSidePercent = parseFloat(localStorage.getItem(dividedContentMainWidthPercentLocalStorrageToken));

        if (!$("body").hasClass("body-small")) {
            currentSideOpened = localStorage.getItem(dividedContentOpenedLocalStorrageToken) ?
                localStorage.getItem(dividedContentOpenedLocalStorrageToken) === "true" :
                ($container.hasClass("divided-content-side-opened") || (!$container.hasClass("divided-content-side-opened") && !$container.hasClass("divided-content-side-closed")) ? true : $(window).width() > 1400);
        }
        else {
            currentSideOpened = false;
        }

        if (isNaN(currentSidePercent)) currentSidePercent = 70;
        lastCoordinateDifference = getdividedContentCoordinateDifferacne(currentSidePercent, this);
        setDividedContentWidth(lastCoordinateDifference, $(".divided-content-main"), $(".divided-content-side"));

        if (currentSideOpened) {
            $container.addClass("divided-content-side-opened").removeClass("divided-content-side-closed");
            $(this).find(".divided-content-toggle-open").addClass("hidden");
            $(this).find(".divided-content-toggle-close").removeClass("hidden");
        }
        else {
            $container.removeClass("divided-content-side-opened").addClass("divided-content-side-closed");
            $(this).find(".divided-content-toggle-open").removeClass("hidden");
            $(this).find(".divided-content-toggle-close").addClass("hidden");
        }

        $toggleButton.on("click", function () {
            if ($(this).closest(".divided-content").hasClass("divided-content-side-opened")) {
                $(this).closest(".divided-content").removeClass("divided-content-side-opened").addClass("divided-content-side-closed");
                $(this).find(".divided-content-toggle-open").removeClass("hidden");
                $(this).find(".divided-content-toggle-close").addClass("hidden");
                $("ul.dropdown-menu.show-hide-column").removeClass("push-left");
                localStorage.setItem(dividedContentOpenedLocalStorrageToken, "false");
            }
            else {
                $(this).closest(".divided-content").addClass("divided-content-side-opened").removeClass("divided-content-side-closed");
                $(this).find(".divided-content-toggle-open").addClass("hidden");
                $(this).find(".divided-content-toggle-close").removeClass("hidden");
                $("ul.dropdown-menu.show-hide-column").addClass("push-left");
                localStorage.setItem(dividedContentOpenedLocalStorrageToken, "true");
            }

            setTimeout(function () {
                let $listTable = $(".divided-content-main").find("table.dataTable, .list-table table, table.list-table");
                var isPayOrder = $.grep($listTable, function (e) { return e.id === "payorders"; });

                if (isPayOrder.length > 0) {
                    $("#payorders").DataTable().columns.adjust().responsive.recalc();
                } else if ($listTable.length > 0 && $listTable.DataTable()) {
                    $listTable.DataTable().columns.adjust().draw();
                }
            }, 500);
        });
    }

    let dividedContentMouseDown = false;
    let mouseStartCoordinates;
    let coordinateDifference;
    $(".divided-content-resizer").on("mousedown touchstart", function (e) {
        dividedContentMouseDown = true;
        // append resize backdrop to prevent any drag blockers (like iframe content etc..)
        $('.divided-content').append('<div class="divided-content-resize-backdrop"></div>')

        var touch = e.originalEvent.pageX ? e.originalEvent : (e.originalEvent.touches[0] || e.originalEvent.changedTouches[0]);
        mouseStartCoordinates = { x: touch.pageX, y: touch.pageY };
    });

    $(window).on("resize", function () {
        lastCoordinateDifference = getdividedContentCoordinateDifferacne(currentSidePercent, $container);
    });

    $("body").on("mouseup touchend", function () {
        if (!dividedContentMouseDown) return;

        $('.divided-content-resize-backdrop').remove();

        dividedContentMouseDown = false;
        lastCoordinateDifference += coordinateDifference;
        localStorage.setItem(dividedContentMainWidthPercentLocalStorrageToken, currentSidePercent);
    });

    $("body").on("mousemove touchmove", function (e) {
        if (!dividedContentMouseDown || !mouseStartCoordinates) return;

        var touch = e.originalEvent.pageX ? e.originalEvent : (e.originalEvent.touches[0] || e.originalEvent.changedTouches[0]);
        coordinateDifference = touch.pageX - mouseStartCoordinates.x;

        let currentCoordinateDifference = coordinateDifference + lastCoordinateDifference
        if (currentCoordinateDifference == 0) return;

        var sidePerc = setDividedContentWidth(currentCoordinateDifference, $(".divided-content-main"), $(".divided-content-side"));
        if (paw.utils.value.isSet(sidePerc)) {
            currentSidePercent = sidePerc;
        }
    })

    if ($(this).find(".document-body").length > 0) $(this).find(".divided-content-main .placeholder").prependTo($(this).find(".document-body"));

    if ($(this).find(".divided-content-main .placeholder").length === 0) {
        $(this).find(".document-table").css("display", "block");
    }
    else {
        var $mutationObserverObject = $(this).find(".document-table");
        $mutationObserverObject.css("display", "none");

        var observe = function () {
            var observer = new MutationObserver(function (mutations, observer) {
                if ($mutationObserverObject.find("tbody").is(':empty')) {
                    $mutationObserverObject.css("display", "none");
                    $mutationObserverObject.closest(".divided-content-main").find(".placeholder").removeClass("hidden");
                }
                else {
                    $mutationObserverObject.css("display", "block");
                    $mutationObserverObject.closest(".divided-content-main").find(".placeholder").addClass("hidden");
                }
            });
            observer.observe(document.querySelector('.document-table'), { childList: true, subtree: true });
        }
        observe();
    }

    function setDividedContentWidth(dividedContentcoordinateDifference, $main, $side) {
        if (!dividedContentcoordinateDifference || isNaN(dividedContentcoordinateDifference)) return;

        let containerWidth = $main.closest(".divided-content").width();
        let baseWidthPx = containerWidth / 100 * 70;

        var offsetDelta = 45 / containerWidth; // 45 = 45px left offset of side panel
        let mainDelta = 1 / containerWidth * (baseWidthPx + dividedContentcoordinateDifference);
        var sideDelta = 1 - (mainDelta - offsetDelta);

        // when deltas > 1 don't set containers' dimensions to prevent container overflow
        if (sideDelta + offsetDelta > 1) {
            return;
        }

        // avoid rounding mistakes
        let rfactor = Math.pow(10, 4);
        var mainPerc = Math.round(mainDelta * 100 * rfactor) / rfactor;
        var sidePerc = Math.round((sideDelta - offsetDelta) * 100 * rfactor) / rfactor;

        $main.css("width", mainPerc + "%");
        $side.css("width", sidePerc + "%");

        let sideWidthPx = containerWidth / 100 * sidePerc;
        $(".tabs-list").css("min-width", sideWidthPx > 600 ? sideWidthPx : 600);

        return mainPerc;
    }
};

$(document).ready(function () {
    $(".divided-content").dividedContent();
});