/// <reference path="Constants.js" />
/// <reference path="../lib/DynamicsPortalToolkit.js" />

if (typeof (Avanade) == "undefined") { Avanade = { __namespace: true }; }
if (typeof (Avanade.Leonardo) == "undefined") { Avanade.Leonardo = { __namespace: true }; }

Avanade.Leonardo.TechnicalPublicationsIndex = new function () {

    var _self = this;
    const fetchs = Avanade.Leonardo.Constants.fetchUrl;
    const homeurl = "https://" + window.location.host;
    const language = $('html').attr('data-lang');
    var urlLanguagePreference = "/" + $('html').attr('data-lang');
    var columnLabels = {
        lnd_integrationkey: "Publication Code",
        lnd_typecode: "Publication Type Code",
        lnd_typeclass: "Operator Type",
        lnd_class: "Class",
        lnd_issue: "Issue",
        lnd_issuedate: "Issue Date",
        lnd_revision: "Revision",
        lnd_revisiondate: "Revision Date",
        lnd_title: "Publication Title",
        lnd_dttemprev: "TR Date"
    };

    function AppendTableBody(tableid) {
        var selector = $('#' + tableid);
        selector.find('thead').after("<tbody>" + "</tbody>");
    };

    function AppendTableHead(tableid, columns) {
        var selector = $('#' + tableid);
        selector.append("<thead><tr></tr></thead>");
        var tRow = $('#' + tableid).find('thead').find('tr');

        columns.forEach(function (item, index) {
            if (item.hidden == true && item.nameattribute != null)
                tRow.append("<th class='lnd-hidden' name='" + item.nameattribute + "'>" + item.name + "</th>");
            else if (item.hidden == false && item.nameattribute != null)
                tRow.append("<th name='" + item.nameattribute + "'>" + item.name + "</th>");
            else
                tRow.append("<th>" + item.name + "</th>");

        });
    };

    function AddDataTable(tableid) {

        if (language == "it-IT") {
            $.fn.dataTable.moment('DD/MM/YYYY');
        } else {
            $.fn.dataTable.moment('MM/DD/YYYY');
        }
        var mainTable = $('#' + tableid).DataTable({
            "order": [],
            "paging": false,
            "info": false,
            "searching": false,
            "scrollY": "400px",
            "scrollCollapse": true,
            "pageLength": 50,
            "fixedHeader": true,
            "autoWidth": false,
            "drawCallback": function () { $('.dataTables_scrollBody thead tr').css({ visibility: 'collapse' }); }
        });
    };

    function RemoveAndDestroy(tableid) {
        var tableSelector = $('#' + tableid);
        if (tableSelector.length != 0) {
            tableSelector.DataTable().destroy();
            tableSelector.remove();
        }
    };

    function FetchGetAllPublications(pageNumber, idsPublicationsToBeExcluded, idsHelicopterModels, classStr, model, operatorType, operatorLabels, searchFilter, operatorValues) {
        const url = Avanade.Leonardo.Constants.url + urlLanguagePreference;
        var search = encodeURIComponent(searchFilter);
        const urlToRequest = url + fetchs.GetAllPublications + "/?count=50&page=" + pageNumber + "&ids=" + idsPublicationsToBeExcluded + "&idsHelicopterModels=" + idsHelicopterModels + "&classStr=" + classStr + "&model=" + model + "&operatorType=" + operatorType + "&operatorLabels=" + operatorLabels + "&searchFilter=" + search + "&operatorValues=" + operatorValues;

        var result = Dynamics.Portal.Fetch.executeWithReturn(urlToRequest, "");
        if (result === null)
            result = [];

        return result;
    };

    function FetchGetAllPublicationsCount(idsPublicationsToBeExcluded, idsHelicopterModels, classStr, model, operatorType, operatorLabels, searchFilter, operatorValues) {
        const url = Avanade.Leonardo.Constants.url + urlLanguagePreference;
        var search = encodeURIComponent(searchFilter);
        const urlToRequest = url + fetchs.GetAllPublicationsCount + "/?ids=" + idsPublicationsToBeExcluded + "&idsHelicopterModels=" + idsHelicopterModels + "&classStr=" + classStr + "&model=" + model + "&operatorType=" + operatorType + "&operatorLabels=" + operatorLabels + "&searchFilter=" + search + "&operatorValues=" + operatorValues;

        var result = Dynamics.Portal.Fetch.executeWithReturn(urlToRequest, "");
        if (result === null)
            result = [{ counter: '0' }];

        return result;
    };

    function FetchGetPublicationsToBeExcluded() {
        const url = Avanade.Leonardo.Constants.url + urlLanguagePreference;
        const urlToRequest = url + fetchs.GetPublicationsToBeExcluded;

        var result = Dynamics.Portal.Fetch.executeWithReturn(urlToRequest, "");
        if (result === null)
            result = [];

        return result;
    };

    function FetchGetHelicopterModelsToBeExcluded() {
        const url = Avanade.Leonardo.Constants.url + urlLanguagePreference;
        const urlToRequest = url + fetchs.GetHelicopterModelsToBeExcluded;

        var result = Dynamics.Portal.Fetch.executeWithReturn(urlToRequest, "");
        if (result === null)
            result = [];

        return result;
    };

    function FetchGetTypeAndClassToBeExcluded() {
        const url = Avanade.Leonardo.Constants.url + urlLanguagePreference;
        const urlToRequest = url + fetchs.GetTypeAndClassToBeExcluded;

        var result = Dynamics.Portal.Fetch.executeWithReturn(urlToRequest, "");
        if (result === null)
            result = [];

        return result;
    };

    function FetchGetModelsForPublicationToBeIncluded(idsHelicopterModels) {
        const url = Avanade.Leonardo.Constants.url + urlLanguagePreference;
        const urlToRequest = url + fetchs.GetModelsForPublications + "/?idsHelicopterModels=" + idsHelicopterModels;

        var result = Dynamics.Portal.Fetch.executeWithReturn(urlToRequest, "");
        if (result === null)
            result = [];

        return result;
    };

    function AppendTable(tableid) {
        var selector = $('#' + tableid + "-tableContent");
        selector.append(""
            + "<table id='" + tableid + "' style='width: 100%; border-collapse: separate; border-spacing: 0 8px;'>"
            + "</table>"
        );
    };

    function paginate(items, itemsPerPage, paginationContainer, currentPage) {
        const totalPages = Math.ceil(items / itemsPerPage);

        function setupPagination() {
            const pagination = document.querySelector(paginationContainer);
            pagination.innerHTML = "";

            if (items === 0)
                return;
            var deltaItems = (currentPage * 50);
            if (deltaItems > items)
                deltaItems = parseInt(items);
            var link = document.createElement("span");
            if (currentPage == 1)
                link.innerText = "Showing 1 to " + deltaItems + " of " + items + " entries";
            else link.innerText = "Showing " + (((currentPage - 1) * 50) + 1) + " to " + deltaItems + " of " + items + " entries";
            link.style.paddingRight = "400px";
            pagination.appendChild(link);

            link = document.createElement("a");
            link.href = "#";
            link.innerText = "Previous";
            setLinkPage(link, pagination, totalPages);
            pagination.appendChild(link);

            var j = 1;
            if (currentPage > 10) {
                j = currentPage - 9;

                link = document.createElement("a");
                link.href = "#";
                link.innerText = "1";
                link.id = "page1";
                setLinkPage(link, pagination, totalPages);
                pagination.appendChild(link);

                link = document.createElement("a");
                link.href = "#";
                link.innerText = "...";
                setLinkPage(link, pagination, totalPages);
                pagination.appendChild(link);

            }

            for (let i = j; i <= totalPages + 1; i++) {
                var link = document.createElement("a");

                link.href = "#";
                if (i === totalPages + 1)
                    link.innerText = "Next";
                else {
                    link.innerText = i;
                    link.id = "page" + String(i);

                    if (i === currentPage) {
                        link.classList.add("active");
                    }
                }

                setLinkPage(link, pagination, totalPages);

                if (i === j + 11) {
                    link = document.createElement("a");
                    link.href = "#";
                    link.innerText = "...";
                    setLinkPage(link, pagination, totalPages);
                    pagination.appendChild(link);

                    link = document.createElement("a");
                    link.href = "#";
                    link.innerText = totalPages;
                    link.id = "page" + String(totalPages);
                    if (i === currentPage)
                        link.classList.add("active");
                    setLinkPage(link, pagination, totalPages);
                    pagination.appendChild(link);

                    link = document.createElement("a");
                    link.href = "#";
                    link.innerText = "Next";
                    setLinkPage(link, pagination, totalPages);
                    pagination.appendChild(link);

                    break;
                }

                pagination.appendChild(link);
            }
        }

        setupPagination();
    };

    function setLinkPage(link, pagination, totalPages) {
        link.addEventListener("click", (event) => {
            var linkToSelect;
            event.preventDefault();

            const currentActive = pagination.querySelector(".active");

            if (link.innerHTML === "Previous")
                linkToSelect = parseInt(currentActive.innerHTML) - 1;
            else if (link.innerHTML === "Next")
                linkToSelect = parseInt(currentActive.innerHTML) + 1;
            else if (link.innerHTML === "...")
                return;
            else
                linkToSelect = parseInt(link.innerHTML);

            currentActive.classList.remove("active");

            if (linkToSelect > 0 && linkToSelect <= totalPages) {
                //document.getElementById("page" + String(linkToSelect)).classList.add("active");
            }
            else {
                currentActive.classList.add("active");
                linkToSelect = parseInt(currentActive.innerHTML);
            }

            _self.TechnicalPublicationsIndex.OnLoad($('#model_value').val(), $('#operatortype_value').val(), $('#fname').val(), linkToSelect, linkToSelect);
        });
    };

    _self.TechnicalPublicationsIndex = new function () {
        const tableid = "form";
        var columns = [
            {
                name: columnLabels.lnd_integrationkey,
                hidden: false,
                nameattribute: null
            },
            {
                name: columnLabels.lnd_typecode,
                hidden: false,
                nameattribute: null
            },
            {
                name: columnLabels.lnd_title,
                hidden: false,
                nameattribute: null
            },
            {
                name: columnLabels.lnd_issue,
                hidden: false,
                nameattribute: null
            },
            {
                name: columnLabels.lnd_revision,
                hidden: false,
                nameattribute: null
            },
            {
                name: columnLabels.lnd_revisiondate,
                hidden: false,
                nameattribute: null
            },
            {
                name: columnLabels.lnd_dttemprev,
                hidden: false,
                nameattribute: null
            }
        ];

        this.OnLoad = function (model, operatorType, searchFilter, pageNumber, currentPage) {
            Started(model, operatorType, searchFilter, pageNumber, currentPage);
        }

        function Started(model, operatorType, searchFilter, pageNumber, currentPage) {
            RemoveAndDestroy(tableid);
            AppendTable(tableid);
            AppendTableHead(tableid, columns);
            AppendTableBody(tableid);

            //#region GET PUBLICATIONS TO BE EXCLUDED
            var fetchGetPublicationsToBeExcluded = FetchGetPublicationsToBeExcluded();
            var idsPublicationsToBeExcluded = "";

            fetchGetPublicationsToBeExcluded.forEach(function (result) {
                if (result.lnd_publicationid != null && result.lnd_publicationid != "undefined")
                    if (idsPublicationsToBeExcluded != "")
                        idsPublicationsToBeExcluded += ';' + result.lnd_publicationid;
                    else
                        idsPublicationsToBeExcluded += result.lnd_publicationid;
            });
            //#endregion

            //#region GET HELICOPTER MODELS TO BE EXCLUDED
            var fetchGetHelicopterModelsToBeExcluded = FetchGetHelicopterModelsToBeExcluded();
            var idsHelicopterModels = "";

            fetchGetHelicopterModelsToBeExcluded.forEach(function (result) {
                if (result.lnd_helicoptermodelid != null && result.lnd_helicoptermodelid != "undefined")
                    if (idsHelicopterModels != "")
                        idsHelicopterModels += ';' + result.lnd_helicoptermodelid;
                    else
                        idsHelicopterModels += result.lnd_helicoptermodelid;
            });
            //#endregion

            //#region GET TYPE AND CLASS TO BE EXCLUDED
            var fetchGetTypeAndClassToBeExcluded = FetchGetTypeAndClassToBeExcluded();
            var classStr = "";
            var operatorLabels = "";
            var operatorValues = "";

            fetchGetTypeAndClassToBeExcluded.forEach(function (result) {
                if (result.lnd_class != null && result.lnd_class != "undefined")
                    if (classStr != "")
                        classStr += ';' + result.lnd_class;
                    else
                        classStr += result.lnd_class;

                if (result.lnd_labelapplicabilita != null && result.lnd_labelapplicabilita != "undefined")
                    if (operatorLabels != "")
                        operatorLabels += ';' + result.lnd_labelapplicabilita;
                    else
                        operatorLabels += result.lnd_labelapplicabilita;

                if (result.lnd_valoreapplicabilita != null && result.lnd_valoreapplicabilita != "undefined")
                    if (operatorValues != "")
                        operatorValues += ';' + result.lnd_valoreapplicabilita;
                    else
                        operatorValues += result.lnd_valoreapplicabilita;
            });

            classStr = [...new Set(classStr.split(";"))].join(";").replace(/;$/, "");
            operatorLabels = [...new Set(operatorLabels.split(";"))].join(";").replace(/;$/, "");
            operatorValues = [...new Set(operatorValues.split(";"))].join(";").replace(/;$/, "");
            //#endregion

            //#region GET MODELS FOR PUBLICATION TO BE INCLUDED
            var fetchGetModelsForPublicationToBeIncluded = FetchGetModelsForPublicationToBeIncluded(idsHelicopterModels);
            var selectModels = document.getElementById('model_value');
            var selectedModelValue = selectModels.value;
            selectModels.options.length = 1;

            fetchGetModelsForPublicationToBeIncluded.forEach(function (result) {
                if (result.lnd_name != null && result.lnd_name != "undefined" && result.lnd_helicoptermodelid != null && result.lnd_helicoptermodelid != "undefined") {
                    var opt = document.createElement('option');
                    opt.value = result.lnd_helicoptermodelid;
                    opt.innerHTML = result.lnd_name;
                    if (opt.value === selectedModelValue) {
                        opt.selected = true;
                    }
                    selectModels.appendChild(opt);
                }
            });
            //#endregion

            //#region GET TYPE AND CLASS FOR PUBLICATION TO BE INCLUDED
            var selectOperatorTypes = document.getElementById('operatortype_value');
            var selectedOperatorTypeValue = selectOperatorTypes.value;
            selectOperatorTypes.options.length = 1;

            if (operatorLabels != "" && operatorValues != "") {
                var labelsArray = operatorLabels.split(";");
                var valuesArray = operatorValues.split(";");

                var mapLabel = {
                    "CIV": "MIL", //se civile > militare
                    "MIL": "CIV" //se militare > civile
                };

                var mapValue = {
                    "121800000": "121800001",
                    "121800001": "121800000"
                };

                for (var i = 0; i < labelsArray.length; i++) {
                    var originalLabel = labelsArray[i];
                    var originalValue = valuesArray[i];

                    var flippedLabel = mapLabel[originalLabel] || originalLabel;
                    var flippedValue = mapValue[originalValue] || originalValue;

                    var opt = document.createElement('option');
                    opt.value = flippedValue;
                    if (opt.value === selectedOperatorTypeValue) {
                        opt.selected = true;
                    }
                    opt.innerHTML = flippedLabel;
                    selectOperatorTypes.appendChild(opt);
                }
            } else {
                var optMil = document.createElement('option');
                optMil.value = 121800001;
                optMil.innerHTML = "MIL";
                if (optMil.value === selectedOperatorTypeValue) {
                    optMil.selected = true;
                }
                selectOperatorTypes.appendChild(optMil);

                var optCiv = document.createElement('option');
                optCiv.value = 121800000;
                optCiv.innerHTML = "CIV";
                if (optCiv.value === selectedOperatorTypeValue) {
                    optCiv.selected = true;
                }
                selectOperatorTypes.appendChild(optCiv);

            }
            //#endregion

            var fetchGetPublicationsToBeFiltered = FetchGetAllPublications(pageNumber, idsPublicationsToBeExcluded, idsHelicopterModels, classStr, model, operatorType, operatorLabels, searchFilter, operatorValues);
            AppendToTarget(tableid, fetchGetPublicationsToBeFiltered);
            AddDataTable(tableid);

            if (currentPage === null || currentPage === undefined)
                currentPage = 1;

            var fetchGetAllPublicationsCount = FetchGetAllPublicationsCount(idsPublicationsToBeExcluded, idsHelicopterModels, classStr, model, operatorType, operatorLabels, searchFilter, operatorValues);
            paginate(fetchGetAllPublicationsCount[0].counter, 50, "#pagination", currentPage);
        }

        function AppendToTarget(target, result) {

            var selector = $('#' + target).find('tbody');
            if (result == undefined || result == null || result == "")
                return;
            result.forEach(function (result) {
                selector.append(""
                    + "<tr class='Rectangle-Copy-21'>"
                    + "<td>"
                    + result.lnd_integrationkey
                    + "</td>"
                    + "<td>"
                    + result.lnd_typecode
                    + "</td>"
                    + "<td>"
                    + result.lnd_title
                    + "</td>"
                    + "<td>"
                    + result.lnd_issue
                    + "</td>"
                    + "<td>"
                    + result.lnd_revision
                    + "</td>"
                    + "<td>"
                    + result.lnd_revisiondate
                    + "</td>"
                    + "<td>"
                    + result.lnd_dttemprev
                    + "</td>"
                    + "</tr>"
                );
            });
        }
    }
};