var $dataTable;

function initializeClassifications() {
    $("#ClassificationSearch").on("change", function () {
        selectPrintType($("#classif_" + $("#ClassificationSearch option:selected").attr("data-type")), $("#ClassificationSearch option:selected").attr("data-type"), true);
    });

    if ($("#ClassificationSearch > option:selected").length > 0) {
        $("#ClassificationSearch").trigger('change');
    }
}

function getTableData() {
    $dataTable = $('#mainGrid');
    if ($.fn.DataTable.isDataTable('#mainGrid'))
        $dataTable.DataTable().destroy();

    $dataTable.DataTable({
        responsive: false,
        scroller: true,
        scrollX: true,
        info: false,
        fixedColumns: { leftColumns: 2 },
        ajax: {
            url: $dataTable.attr('data-url'),
            data: function (d) {
                d.Classifications = $("#ClassificationQid").val();
                d.DateFrom = null;
                d.DateTo = null;
            }
        },
        order: [[1, 'desc']],
        columns: [
            {
                data: "AcKey", name: "AcKey", className: 'dt-body-center',
                render: function (data, type, full) {
                    if (type === 'display')
                        return $.fn.dataTable.render.previewWithOptions(full.Id, $("#paasPrintDocumentUrl").val(), full.Attachments, "getAttachmentsForDocument(" + full.Id + ")");
                    else
                        return "";
                }
            },
            { data: "AcKeyView", name: "AcKey", filtertype: "text", render: $.fn.dataTable.render.link('Id') },
            { data: "Subject", name: "AcSubject", filtertype: "text" },
            { data: "SubjectName", name: "AcSubjectNavigation.AcName2", filtertype: "text", render: $.fn.dataTable.render.ellipsis(30, false) },
            { data: "Date", name: "AdDate", filtertype: "dateTime" },
            { data: "DateDue", name: "AdDateDue", filtertype: "dateTime" },
            { data: "Title", name: "AcTitle", filtertype: "text" },
            { data: "DocType", name: "AcDocType", filtertype: "text" },
            { data: "Classification", name: "AnClassification.AcTypeDesc", filtertype: "text", render: $.fn.dataTable.render.ellipsis(25, false) },
            { data: "Note", name: "AcNote", filtertype: "text", render: $.fn.dataTable.render.note("Id") },
            { data: "Clerk", name: "AnClerkUser.AcTitle", orderable: false, filtertype: "text" },
            { data: "StatusName", name: "AcStatusNavigation.AcName", orderable: false, filtertype: "text" }
        ]
    });

    $dataTable.on('xhr.dt', function (e, settings, json, xhr) {
        initializeTableHeight();
    });
}

function togglePrintOptionGroup(element, event) {
    event.stopPropagation();
    $(element).closest(".print-option-group").toggleClass("print-group-closed");
}

function selectPrintType($element, type, openTree = false) {
    $("div.custom-option-selected").removeClass("custom-option-selected");
    $($element).addClass("custom-option-selected");
    if (openTree)
        $($element).parents(".print-option-group").removeClass("print-group-closed");

    $.ajax({
        cache: false,
        type: "GET",
        url: $("#getClassificationDataUrl").val(),
        data: {
            type: type
        },
        success: function (data) {
            $("#ClassificationQid").val(data.AnQid);
            $("#Code").val(data.AcType);
            $("#MaterialTypeDesc").val(data.AcTypeDesc);
            $("#MaterialType").val(data.AcDocKind).trigger("change");
            $("#Validity").val(data.AnValidValue);
            $("#ValidityType").val(data.AcValidType);
            $("#Clerk").val(data.AnClerk);
            $("#TopId").selectpicker('val', data.AnTopId);
            $("#EscalationDays").val(data.AnEscalation);
            $("#WorkflowId").val(data.AnWorkflowId);
            $("#Storage").val(data.AnStorageQid);
            $("#Note").val(data.AcNote);
            $("#ClassificationSearch").selectpicker('val', data.AnQid);

            if ($.fn.DataTable.isDataTable('#mainGrid'))
                $.fn.dataTable.reload($('#mainGrid'));
            else
                getTableData();
        },
        error: function (error) {
            console.log("Classification error");
        }
    });
}

function getAttachmentsForDocument(id) {
    swapPreviewIcon(true, ("previewIcon-" + id), "fa fa-eye");
    $("#previewDropdown-" + id).empty();

    $.get($("#getAttachmentsForDocumentUrl").val(), { qid: id })
        .done(function (response) {
            var func = $("#paasPrintDocumentUrl").val().replace("{0}", id);

            if (response.length === 1) {
                openPdfPreview($("#paasPrintDocumentUrlOnly").val().replace("{0}", id).replace("{1}", response[0].AttachmentId));
            } else {
                response.forEach(attachment => {
                    $("#previewDropdown-" + id).append("<li><a onClick=\"" + func.replace("{1}", attachment.AttachmentId) + "\">" + attachment.Name + "</a></li>");
                });
            }

            swapPreviewIcon(false, ("previewIcon-" + id), "fa fa-eye");
        });
}

function swapPreviewIcon(loading, buttonId, icon) {
    var $button = $("#" + buttonId);
    var $buttonIcon = $button.find("span.eyeIcon");
    var $buttonGroupButtons = $button.parent().find("button");

    if (loading) {
        $buttonIcon.removeClass(icon).addClass("fa fa-spinner fa-spin fa-fw");
    }
    else {
        $buttonIcon.removeClass("fa fa-spinner fa-spin fa-fw").addClass(icon);
    }
}

function swapLoadingIcon(loading, buttonId, icon) {
    var $button = $("#" + buttonId);
    var $buttonIcon = $button.find("i");
    var $buttonGroupButtons = $button.parent().find("button");

    if (loading) {
        $buttonIcon.removeClass(icon).addClass("fa fa-spinner fa-spin fa-fw");
        $buttonGroupButtons.attr("disabled", true);
    }
    else {
        $buttonIcon.removeClass("fa fa-spinner fa-spin fa-fw").addClass(icon);
        $buttonGroupButtons.removeAttr("disabled");
    }
}

function openPdfPreview(url) {
    loadPdfPanelContentPAAS($("#pdfPanel"), url, true);
}

function updateClassification() {
    swapLoadingIcon(true, "saveButton", "fa fa-save");

    var model = {
        AnQid: $("#ClassificationQid").val(),
        AcType: $("#Code").val(),
        AcTypeDesc: $("#MaterialTypeDesc").val(),
        AcDocKind: $("#MaterialType").val(),
        AnValidValue: $("#Validity").val(),
        AcValidType: $("#ValidityType").val(),
        AnClerk: $("#Clerk").val(),
        AnTopId: $("#TopId").val(),
        AnEscalation: $("#EscalationDays").val(),
        AnWorkflowId: $("#WorkflowId").val(),
        AnStorageQid: $("#Storage").val(),
        AcNote: $("#Note").val()
    };

    $.ajax({
        type: "POST",
        data: JSON.stringify(model),
        url: $("#ClassificationQid").val() ? $("#updateClassificationUrl").val() : $("#createClassificationUrl").val(),
        contentType: "application/json"
    }).done(function (response) {
        swapLoadingIcon(false, "saveButton", "fa fa-save");
        if (response) {
            window.location.reload();
        } else {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "error",
                text: $("#ErrorSavingLoc"),
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: $("#ConfirmLoc").val(),
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }
    });
}

function newClassification() {
    $("#ClassificationQid").val("");
    $("#Code").val("");
    $("#Code").val("");
    $("#MaterialTypeDesc").val("");
    $("#MaterialType").val("");
    $("#Validity").val(0);
    $("#ValidityType").val("");
    $("#Clerk").val("");
    $("#TopId").selectpicker('val', "");
    $("#EscalationDays").val("");
    $("#WorkflowId").val("");
    $("#Storage").val("");
    $("#Note").val("");
    $("#ClassificationSearch").selectpicker('val', "");
}

// Import classifications
function openImportClassificationModal() {
    let tableTitles = [$("#CodeLoc").val(), $("#MaterialTypeDescLoc").val(), $("#MaterialTypeLoc").val(), $("#ValidityLoc").val(), $("#ValidityTypeLoc").val(), $("#NoteLoc").val()];
    let tableDataNames = ["Type", "TypeDesc", "DocKindText", "ValidValue", "ValidTypeText", "Note" ];
    let localization = {
        importType: $("#ImportTypeLoc").val(),
        forCountry: $("#ForCountryLoc").val(),
        dowloadFromServer: $("#DownloadFromServerLoc").val(),
        importIntoCodebook: $("#ImportIntoCodebookLoc").val(),
        importTypeAdding: $("#ImportTypeAddingLoc").val(),
        importTypeAddEdit: $("#ImportTypeAddEditLoc").val(),
        yesNo: $("#YesLoc").val() + "/" + $("#NoLoc").val()
    };

    openImportCodebookModal($("#ImportClassificationsLoc").val(), tableTitles, tableDataNames,
        $("#GetImportClassificationsUrl").val(), $("#ImportClassificationsUrl").val(), $("#ImportSettingsClassificationUrl").val(),
        localization,
        $("#CurrentUserLocalization").val(),
        function () {
            $.fn.dataTable.reload($('#grid-data'));
        },
        function (data) {
            data.group = $(".codebook-group").val();
            data.code = $(".codebook-code").val();
            data.desc = $(".codebook-description").val();
        },
        "<div class='col-sm-8 m-t-xs'><label>" + $("#GroupLoc").val() + "</label><select class='form-control codebook-group'></select></div>" +
        "<div class='col-sm-8 m-t-xs'><label>" + $("#TheCodeLoc").val() + "</label><input class='form-control codebook-code' /></div>" +
        "<div class='col-sm-8 m-t-xs'><label>" + $("#DescriptionLoc").val() + "</label><input class='form-control codebook-description' /></div>",
        function (data) {
            if (data.ClassificationGroup && $(".codebook-group").children().length === 0) {
                for (let i = 0; i < data.ClassificationGroup.length; i++) {
                    let classificationGroup = data.ClassificationGroup[i];
                    let displayText = classificationGroup.AcName === null ? classificationGroup.AcID : classificationGroup.AcID + " - " + classificationGroup.AcName;
                    $(".codebook-group").append("<option value='" + (classificationGroup.Group === null ? "" : classificationGroup.AcID) + "'>" + displayText + "</option>");
                }
            }
        }
    );
}

var heightInitialized = false;
function initializeTableHeight() {

    if (heightInitialized) {
        return;
    }
    heightInitialized = true;

    var rectTop = document.getElementById("mainGrid").getBoundingClientRect().top;
    var rectBottom = document.body.scrollHeight;

    let offset = 20;
    let dtHeight = (rectBottom - rectTop - offset) + "px";

    $(".dataTables_scrollBody").css("height", dtHeight);
    $(".dataTables_scrollBody").css("min-height", dtHeight);
}