// Date: 23.04.2021
// Add showhidecolumns class and data-grid-id attribute to table element, and data-column-id on every th element
// Add data-default-hidden for elements that should be hidden on first load
// Note: Not working when there are multiple tables on same page 

var editedTable = false;
var tableHead = $(".showhidecolumns > thead > tr");
var table = $(".showhidecolumns");
var node = $(".showhidecolumns > tbody")[0];
var tableData;

$(document).ready(function () {
    if ($(".showhidecolumns").data("dynamic-table") || table.length === 0)
        return;

    displayShowHideDropdown();
});

function displayShowHideDropdown() {
    getTableConfiguration().done(function () {
        setDropdownMenu();

        // Delete duplicated select2 items
        if ($("#identRows tr").length === 1) {
            $("#identRows tr:first td .select2withAPI").each(function () {
                var numOfSameSelect2Items = $(this).siblings("span").length;

                if (numOfSameSelect2Items > 1) {
                    $(this).siblings("span").last().remove();
                };
            });
        }
    });
}

function setDropdownMenu() {
    var showHideColumnsTitle = $("#ShowHideColumns").val();
    var dropdownMenu = `<span id="sh-dropdown-menu" class="showHideDropdown" title="${showHideColumnsTitle}">
            <a role='button' class='pull-right'>
                <span class='default-icon-color'>   
                    <i class='fas fa-ellipsis-v'></i>
                </span>
            </a>
            <ul class='dropdown-menu sh-dropdown-position' id='show-hide-list'></ul>
        </span>`;

    addPaddingToLastElement();

    if ($("#sh-dropdown-menu").length < 1) {
        table.append(dropdownMenu);
        populateDropdownBT();
        openCloseDropdown();
    }

    // TODO: Find smarter fix for tabindex="-1"
    fixTabIndexOnDailyWages()
}

function fixTabIndexOnDailyWages() {
    setTimeout(function () {
        $(".select2-selection--single").each(function () {
            $(this).removeAttr("tabindex");
            $(this).attr("tabindex", "0");
        });

        $("#createDailyWageValueBtn").attr("tabindex", "0");
        $("#createMileageBtn").attr("tabindex", "0");
    }, 100)
}

function addPaddingToLastElement() {
    $(table).find('thead > tr > th:last').css("padding-right", "25px");
}

function removePaddingFromLastElement() {
    $(table).find('thead > tr > th:last').css("padding-right", "unset");
}

// Populate Show/Hide dropdown with column names
function populateDropdownBT() {
    $(table).find('thead > tr > th').each(function (index) {
        var text = $(this).text().trim();
        var columnId = $(this).data("column-id");
        var defaultHidden = $(this).data("default-hidden");

        if ($(this).data("column-id") === "Photo") {
            text = $("#Picture").val();
        }

        if (tableData && tableData.TableName != null) {
            var columnData = tableData.Columns.filter(el => { return el.Id === columnId })[0];
        }

        if (columnData != null && columnData.IsHidden) {  
            isChecked = 0;
            $(this).addClass("hidden-column");
            $(table).find("tbody > tr > td:nth-child(" + (index + 1) + ")").addClass("hidden-column");
        } else {
            var isChecked = 1;
        }

        if (!columnData && (defaultHidden === true || defaultHidden === "True")) {
            isChecked = 0;
            $(this).addClass("hidden-column");
            $(table).find("tbody > tr > td:nth-child(" + (index + 1) + ")").addClass("hidden-column");
        }

        var hidden = text == "" || text == null ? "hidden" : "";
        var listItem = `
                <li class='${hidden}'>
                    <label class="custom-checkbox-container">
                        <input type='checkbox' data-column='${index}' name='PREF${columnId}' class='custom-checkbox custom-dirty-checker-ignore sh-checkbox' ${isChecked ? 'checked' : ''} />
                        ${text}
                        <span class="custom-checkbox-checkmark"></span>
                    </label>
                </li>`;

        $('#show-hide-list').append(listItem);
    });
}

function openCloseDropdown() {
    $('#sh-dropdown-menu a').on('click', function (event) {
        $(this).parent().toggleClass('open');
    });

    $('body').on('click', function (e) {
        if (!$('#sh-dropdown-menu').is(e.target)
            && $('#sh-dropdown-menu').has(e.target).length === 0
            && $('.open').has(e.target).length === 0
        ) {
            $('#sh-dropdown-menu').each(function (index) {
                $(this).removeClass('open');
            });
        }
    });
    editedTable = false;
}

$(document).on('click', '.sh-checkbox', function () {
    var checked = $(this).is(":checked");
    var columnId = $(this).attr("name");
    columnId = columnId.slice(4);
    var th = $('thead > tr > th[data-column-id="' + columnId + '"]');
    editedTable = true;

    if (checked) {
        $(this).prop('checked', true);
        th.removeClass("hidden-column");
        th.attr("visible", true);
        $(table).find("tbody > tr > td:nth-child(" + (th.index() + 1) + ")").removeClass("hidden-column");
    } else {
        $(this).prop('checked', false);
        th.addClass("hidden-column");
        th.attr("visible", false);
        $(table).find("tbody > tr > td:nth-child(" + (th.index() + 1) + ")").addClass("hidden-column");
    }

    saveTableConfiguration();
});

$('.showhidecolumns > thead > tr').sortable({
    cursor: "move",
    placeholder: "ui-state-highlight",
    opacity: 0.7,
    helper: "clone",
    axis: 'x',
    items: 'th:not([data-sortable])',
    start: function (e, ui) {
        removePaddingFromLastElement();
        var ind_th = ui.item.index();
        $('.showhidecolumns > tbody > tr').each(function (ind, el) {
            $('td', el).eq(ind_th).addClass('drg');
        });
    },
    stop: function (e, ui) {
        var itInd = ui.item.index();
        $(".showhidecolumns > tbody > tr").each(function (ind, el) {
            var cell = $(".drg", el).detach();
            if (itInd >= $("td", el).length) {
                cell.appendTo($(el));
            } else {
                cell.insertBefore($("td", el).eq(itInd));
            }
            cell.removeClass("drg");
        });
        addPaddingToLastElement();
        editedTable = true;
    }
}).disableSelection();

function saveTableConfiguration() {
    let columns = [];
    let column = {};
    var tableName = table.attr('data-grid-id');

    $(table).find("thead > tr > th").each(function () {
        var columnId = $(this).data("column-id");
        var th = $("thead > tr > th[data-column-id='" + columnId + "']");
        var position = th.index();
        var isHidden = $(this).hasClass("hidden-column");
        var width = $(this).innerWidth();

        column = {
            Id: columnId,
            Position: position,
            IsHidden: isHidden,
            Width: width
        };
        columns.push(column);
    });

    $.ajax({
        url: $("#SaveTableGrid").val(),
        method: 'POST',
        data: {
            TableName: tableName,
            Columns: columns
        },
        success: function () {
            tableData.TableName = tableName;
            tableData.Columns = columns;
        }
    });
}
function getTableConfiguration() {
    var tableName = table.attr('data-grid-id');

    return $.ajax({
        url: $("#GetTableGrid").val(),
        data: {
            TableName: tableName
        },
        success: function (data) {
            if (jQuery.isEmptyObject(data) && tableName && tableName.includes("create-order")) {
                select2withAPI();
                tableData = null;
                return;
            }
            if (!jQuery.isEmptyObject(data) && !table.hasClass("not-sortable")) {
                tableData = data;
                reorderColumns();
                resizeTable();
                initializeDateTimePicker();
            }
        }
    });
}

window.onbeforeunload = function () {
    if (editedTable) {
        saveTableConfiguration();
    }
}

function reorderColumns(reload, newRow) {
    if (!tableData || jQuery.isEmptyObject(tableData)) return;
    if ($(table).hasClass("no-table-reorder")) return;

    var colOrder = [];
    var dataOrder = [];

    $(table).find('thead > tr > th').each(function (i) {

        var columnId = $(this).data("column-id");
        var columnData = tableData.Columns.filter(el => { return el.Id === columnId })[0];
        if (columnData) {
            if (!reload && isNaN(parseInt($(this).attr("data-column-position")))) {
                colOrder[i] = columnData.Position;
            }
            else {
                dataOrder[i] = parseInt($(this).attr("data-column-position"));
                colOrder[dataOrder[i]] = i;
            }

        }
    });

    if (!dataOrder || dataOrder.length === 0) {
        colOrder.forEach(function (i, item) {
            dataOrder.push(colOrder.indexOf(item));
        });
    }

    let orderObjects = $(table).find('tr');
    if (reload) orderObjects = $(newRow).length == 0 ? $(table).find('tr').last() : $(newRow)[0];

    destroySelect2WithAPI();

    $(orderObjects).html(function (i) {
        return $(this).children().sort(function (a, b) {
            var aOrder = colOrder[$(a).index()],
                bOrder = colOrder[$(b).index()];

            return aOrder - bOrder;
        });
    });

    //bind Twitter Bootstrap tooltips
    $('body').tooltip({
        selector: '[rel=tooltip]'
    });

    if (tableData.TableName.includes("create-order-")) {
        reload = true;
    }

    if (reload) {
        $(table).find('thead > tr > th').each(function (i) {
            let hideColumn = $(table).find('thead > tr > th').eq(i).hasClass("hidden-column");
            if (hideColumn) {
                $(orderObjects).each(function (j, row) {
                    $(row).find("td").eq(i).addClass("hidden-column");
                });
            }
        });
    }

    $(table).find('thead > tr > th').each(function (i) {
        $(this).attr("data-column-position", dataOrder[i]);
    });

    if ($(newRow).length == 0 || ($(newRow).length > 0 && !$(newRow).data('select2'))) 
        select2withAPI();

    $(".custom-select").customSelect();

    $(table).find("tbody > tr .select2withAPI").each(function () {
        let selectSiblings = $(this).siblings();
            
        if (selectSiblings.length > 1) {
            selectSiblings.last().remove();
        }
    });
}

function destroySelect2WithAPI() {
    $(table).find("tbody > tr").each(function () {
        $(this).find(".select2HideColumns select").select2("destroy");
    });
}

//#region Resize columns
for (var i = 0; i < table.length; i++) {
    resizableGrid(table[i]);
}

function resizeTable() {
    var colOrder = {};
    $(table).find('thead > tr > th').each(function (i) {
        var columnId = $(this).data("column-id");
        var columnData = tableData.Columns.filter(el => { return el.Id === columnId })[0];
        if (columnData) {
            colOrder[i] = columnData.Position;
            $(this).innerWidth(columnData.Width);
        }
    });
}

function resizableGrid(table) {
    var row = table.getElementsByTagName('tr')[0],
        cols = row ? row.children : undefined;
    if (!cols) return;

    var tableHeight = table.offsetHeight;

    for (var i = 0; i < cols.length; i++) {
        var div = createDiv(tableHeight);
        cols[i].appendChild(div);
        cols[i].style.position = 'relative';
        setListeners(div);
    }

    function setListeners(div) {
        var pageX, curCol, nxtCol, curColWidth, nxtColWidth;

        div.addEventListener('mousedown', function (e) {
            $('.showhidecolumns > thead > tr').sortable('disable');
            curCol = e.target.parentElement;
            nxtCol = curCol.nextElementSibling;
            pageX = e.pageX;

            var padding = paddingDiff(curCol);

            curColWidth = curCol.offsetWidth - padding;
            if (nxtCol)
                nxtColWidth = nxtCol.offsetWidth - padding;
            editedTable = true;
        });

        div.addEventListener('mouseover', function (e) {
            e.target.style.borderRight = '1px solid gray';
        })

        div.addEventListener('mouseout', function (e) {
            e.target.style.borderRight = '';
        })

        row.addEventListener('mousemove', function (e) {
            if (curCol) {
                var diffX = e.pageX - pageX;

                if (nxtCol)
                    nxtCol.style.width = (nxtColWidth - (diffX)) + 'px';

                curCol.style.width = (curColWidth + diffX) + 'px';
            }
        });

        document.addEventListener('mouseup', function (e) {
            curCol = undefined;
            nxtCol = undefined;
            pageX = undefined;
            nxtColWidth = undefined;
            curColWidth = undefined
            $('.showhidecolumns > thead > tr').sortable("option", "disabled", false);
        });
    }

    function createDiv(height) {
        var div = document.createElement('div');
        div.style.top = 0;
        div.style.right = 0;
        div.style.width = '5px';
        div.style.position = 'absolute';
        div.style.cursor = 'col-resize';
        div.style.userSelect = 'none';
        div.style.height = height + 'px';
        return div;
    }

    function paddingDiff(col) {

        if (getStyleVal(col, 'box-sizing') == 'border-box') {
            return 0;
        }

        var padLeft = getStyleVal(col, 'padding-left');
        var padRight = getStyleVal(col, 'padding-right');
        return (parseInt(padLeft) + parseInt(padRight));
    }

    function getStyleVal(elm, css) {
        return (window.getComputedStyle(elm, null).getPropertyValue(css));
    }
};
////#endregion