/*!
 * iSchedulerReport area Editor.js v1.0.0
 *
 * Copyright (c) Vonalkód Rendszerház 
*/

/*##### SELECTORS' CASH #####*/
var selCash;
function EditorSelectors() {
    this.$PackageName = $('#PackageName');
    this.$PackageRoleName = $('#PackageRoleName');
    this.$rolenames = $('#role-names');
    this.$reports = $('#PackageReportsSelected');
}
/*##### SELECTORS' CASH END #####*/

/*##### GLOBAL VARIABLES #####*/
var constEditor = new EditorConstants();    //!!! ennek az objektumnak kell értéket adni a cshtml-ben !!!
var thisjs = 'iSchedulerReport.Editor.js: ';
/*##### GLOBAL VARIABLES END #####*/

/*##### EVENTS #####*/
$(document).ready(function () {
    'use strict';

    var thisfn = thisjs + 'READY event';
    console.log(thisfn);
    EditorConstantsInit(); //AutoCompInit előtt kell lennie !!!
    selCash = new EditorSelectors();
    //console.log(thisjs + 'constEditor selCash', constEditor, selCash);

    //Autocomplete inicializálás
    var inp1 = 'PackageRolegroups';
    var inp2 = 'PackageUsers';
    var sel = 'Selected';
    vrhct.autocomplete.init({ textName: inp1 + sel, valueName: inp1, isMultiList: true, url: constEditor.URL_ROLEGROUPLIST });
    vrhct.autocomplete.init({ textName: inp2 + sel, valueName: inp2, isMultiList: true, url: constEditor.URL_USERLIST });

    changePackageName(); //rolename előzetes beállítása

    vrhct.masterdata.addClass('#' + constEditor.EditorFormId, 'input[type=text]');

    addReportItem(constEditor.SelectedReports, constEditor.SelectedFormats);

    $('#' + constEditor.EditorFormId).on("submit", function (e) {
        //e.preventDefault(); // cancel the actual submit
        $('#' + constEditor.EditorDialogId).find('#buttoncontainer').hide();
        $('#' + constEditor.EditorDialogId).find('#waitmessagecontainer').show();
        //return false; //nem folytatja a submit-ot
    });
});
/*##### EVENTS  END #####*/


/*##### METHODS #####*/

/**
 * Ha megváltozik a csomag neve, akkor a hozzá tartozó szerep neve is változik. 
 */
function changePackageName() {
    'use strict';
    var pckname = selCash.$PackageName.val();
    var rolename = constEditor.ROLENAMEMASK;
    while (rolename.includes(constEditor.VAR_PCKNAME)) rolename = rolename.replace(constEditor.VAR_PCKNAME, pckname);
    selCash.$PackageRoleName.val(rolename);
}// changePackageName function END

/**
 * Egy sor törlése a riportok táblázatból
 * 
 * @param {any} id A törlendő sor azonosítója.
 */
function deleteReportItem(id) {
    'use strict';
    var $item = $('.selector-class-for-reports#' + id);
    console.log(thisjs + 'deleteReportItem: item', $item);
    $('.selector-class-for-reports#' + id).remove();
}

/**
 * Egy riport hozzáadása a riportok táblázathoz.
 * 
 * @param {any} initReports
 * @param {any} initFormats
 */
function addReportItem(initReports, initFormats) {
    'use strict';
    //A már meglévő két lista birtokában a sorok beillesztése
    function addRow(reportlist, formatlist)
    {
        function getRow(id, report, format) {
            var ret = '<tr id="' + id + '" class="selector-class-for-reports">'
                + '<td class="package-item-riports"><select id="SelectedReports" name="SelectedReports" class="form-control form-control-sm selector-reportid">';
            for (var i = 0; i < reportlist.length; i++) {
                var slctd = reportlist[i].Value == report ? 'selected' : '';
                ret += '<option value="' + reportlist[i].Value + '" ' + slctd + '>' + reportlist[i].Text + '</option>';
            }
            ret += '</select></td><td class="package-item-formats"><select id="SelectedFormats" name="SelectedFormats" class="form-control form-control-sm selector-exporttype">';
            for (var i = 0; i < formatlist.length; i++) {
                var slctd = formatlist[i].Value == format ? 'selected' : '';
                ret += '<option value="' + formatlist[i].Value + '" ' + slctd + '>' + formatlist[i].Text + '</option>';
            }
            ret += '</select></td><td class="package-item-operations">'
                + '<span class="fas fa-trash-alt" onclick="deleteReportItem(' + id + ');"></span>'
                 + '</td></tr>';;
            return(ret);
        }// getRow function END

        var id = 0;
        var rows = '';
        var selectedvalues = [];

        if (initReports && initReports.length > 0) {
            //ha van init, akkor ez a kezdeti hívás
            for (var i = 0; i < initReports.length; i++) {
                selectedvalues.push(initReports[i]);
                rows += getRow(id, initReports[i], initFormats[i]);
                id++;
            }
            $('#package-report-items').html(rows);
            //diagwait.modal('hide');
        } else {
            //ha nincs init, akkor le kell kérdezni az eddig kiválasztott reportazonosítókat
            var selectedReports = $(".selector-class-for-reports");
            console.log('selectedReports', selectedReports);
            if (selectedReports && selectedReports.length > 0) {
                for (var i = 0; i < selectedReports.length; i++) {
                    selectedvalues.push($(selectedReports[i]).find(".selector-reportid").val());
                    id++;
                 }
            }
            console.log('selectedvalues', selectedvalues);

            var newValue = '';
            for (var i = 0; i < reportlist.length; i++) {
                if (!selectedvalues.includes(reportlist[i].Value)) {
                    newValue = reportlist[i].Value;
                    break;
                }
            }

            console.log('newValue', newValue);
            //diagwait.modal('hide');
            if (newValue) {
                rows += getRow(id, newValue, formatlist[0]);
                $('#package-report-items').append(rows);
            } else {
                bootbox.alert(constEditor.MESS_NOMOREREPORTSADD);
            }
        }
    }// addRow function END

    var thisfn = thisjs + 'addReportItem: ';
    console.log(thisfn + 'initReports', initReports);

    //lekérem a két listát
    //var diagwait = waitMessageDialog();
    $.ajax({
        url: constEditor.URL_REPORTLIST,
        contenttype: 'application/json',
        datatype: 'json',
        success: function (reportlist) {
            if (!reportlist || reportlist.length == 0) {
                //diagwait.modal('hide');
                bootbox.alert(constEditor.MESS_REPORTSLISTEMPTY);
            } else {
                $.ajax({
                    url: constEditor.URL_FORMATLIST,
                    contenttype: 'application/json',
                    datatype: 'json',
                    success: function (formatlist) {
                        if (!formatlist || formatlist.length == 0) {
                            //diagwait.modal('hide');
                            bootbox.alert(constEditor.MESS_FORMATSLISTEMPTY);
                        } else {
                            addRow(reportlist, formatlist);
                        }
                    },
                    error: function (jqXHR, exception) {
                        //diagwait.modal('hide');
                        console.log(thisfn + 'formatlist: Ajax hívás sikertelen! ', jqXHR.responseText);
                    }
                });
            }
        },
        error: function (jqXHR, exception) {
            //diagwait.modal('hide');
            console.log(thisfn + 'reportlist: Ajax hívás sikertelen! ', jqXHR.responseText);
        }
    });
}// addReportItem function END


function viewUsersOfRole() {
    'use strict';

    var thisfn = thisjs + 'viewUsersOfRole: ';
    var rolename = selCash.$PackageRoleName.val();
    var url = constEditor.URL_USERSOFROLE;
    console.log(thisfn + 'variable="%s"; rolename="%s"; url="%s"', constEditor.VAR_ROLENAME, rolename, url);
    while (url.includes(constEditor.VAR_ROLENAME)) url = url.replace(constEditor.VAR_ROLENAME, rolename);
    console.log(thisfn + 'url', url);
    $.ajax({
        type: "GET",
        url: url,
        success: function (response) {
            console.log(thisjs + thisfn + 'response', response);
            if (response != null && response.length > 0) {
                var mess = '<style>'
                            + '#usersoftheroletable td, th { border: 1px solid; vertical-align: top; padding: 3px; }'
                            + '</style>'
                            + '<table id="usersoftheroletable" style="width:100%;">'
                            + '<tr><th>' + constEditor.LABEL_USER + '</th><th>' + constEditor.LABEL_EMAIL + '</th></tr>';
                for (var i = 0; i < response.length; i++) {
                    mess += '<tr><td>' + response[i].Value + '</td><td>' + response[i].Text + '</td></tr>';
                }
                mess != '</table>';
                bootbox.alert({ message: mess, title: constEditor.TITLE_USERSOFROLE });
            } else {
                bootbox.alert(constEditor.MESS_USERSLISTISEMPTY);
            }
        },
        error: function (jqXHR, exception) {
            console.log(thisjs + thisfn + 'Ajax hívás sikertelen!', jqXHR.responseText);
            bootbox.alert(constEditor.MESS_UNSUCCESSFUL);
        },
    });
}//viewUsersOfRole function END


/**
 * A függvény a törlés rákérdezése után a paraméterben megadott id-val, meghívja
 * a deletePackageURL,-t. Amely következő függvényt hívja az iSchedulerReport controllerben:
 *    public JsonResult DeletePackage(int id){ ... }
 * Ha üres stringgel tér vissza, akkor minden rendben lezajlott, ha nem, akkor az hibaüzenet.
 * 
 * @param {any} packageId A törlendő csomag egyedi azonosítója.
 * @param {any} sourceOfCalling Honnan indították az Editor-t. HA a Managerből, akkor az ott lévő táblát is frissíti.
 */
function deleteTheEntirePackage(packageId, sourceOfCalling) {
    'use strict';

    try {
        var thisfn = 'Editor.js: deleteTheEntirePackage function: '
        var packageName = $('#PackageName').val();
        var packageDescription = $('#PackageDescription').val();
        console.log(thisfn + 'packageId="%s", packageName="%s", packageDescription="%s", sourceOfCalling="%s"', packageId, packageName, packageDescription, sourceOfCalling);

        var confirmMessage = '<table>'
            + '<tr><td>' + constEditor.labelId + ':</td><td style="padding-left:4px;">' + packageId + '</td></tr>'
            + '<tr><td>' + constEditor.labelName + ':</td><td style="padding-left:4px;">' + packageName + '</td></tr>'
            + '<tr><td>' + constEditor.labelDescription + ':</td><td style="padding-left:4px;">' + packageDescription + '</td></tr>'
            + '</table>'
            + '<br />'
            + '<div style="font-weight:bold;">' + constEditor.confirmDelete + '</div>';

        vrhct.bootbox.delete({
            ajax: {
                url: constEditor.URL_DELETE,
                data: { id: packageId }
            },
            title: constEditor.confirmTitle,
            confirm: confirmMessage,
            shown: function () {
            },
            success: function () {
                console.log(thisfn + 'Sikeres törlés. Itt vagyunk a callback-ben.');
                vrhct.bootbox.hide(constEditor.EditorDialogId);
                if (sourceOfCalling == constEditor.CallSources.Manager) {
                    schrep.PackageTable.Table.draw('page');
                }
           }
        });
    } catch (e) {
        console.error(e);
    }
}// deleteTheEntirePackage function END


/**
 * A mentés utáni visszajelző üzenet megjelenítése.
 * 
 * @param {any} message A megjelenítendő üzenet.
 * @param {any} title Mi legyen az üzenet fejléce.
 * @param {any} isLarge Széles legyen-e az ablak, ami megjeleníti az üzenetet.
 */
function showEditorReturnInfo(message, title, isLarge)
{
    var thisfn = 'Editor.js: showEditorReturnInfo function: ';
    //console.log(thisfn + 'PING message="%s", title="%s", isLarge=%o, SourceOfCalling="%s"', message, title, isLarge, constEditor.SourceOfCalling);
    bootbox.dialog({
        title: title,
        message: message,
        size: isLarge ? 'xl' : '',
        className: 'editorreturninfo',
        onEscape: true,
        onEscape: function () {
            //console.log(thisfn + 'in callback: bootboxid="%s"', constEditor.EditorDialogId);
            if (constEditor.SourceOfCalling === constEditor.CallSources.Manager) {
                schrep.PackageTable.Table.draw('page'); // táblázat frissítése a Manager-ben
            }
            vrhct.bootbox.hide(constEditor.EditorDialogId); // Editor ablak becsukása
        }
    });
}// showEditorReturnInfo function END

/*##### METHODS END #####*/


/** 
 * A szükséges konstansok, melyek a cshtml-ben kapnak értéket.
 * Azért a prototype, hogy gépelés közben legyen intellisense.
 */
function EditorConstants() {
    function CallSourcesType() {
        this.Manager = 'manager';
    }
    this.CallSources = new CallSourcesType();
    /** Honnan hívták az editor-t. */
    this.SourceOfCalling = '';

    // Messages
    this.MESS_WAIT = '';
    this.MESS_WAITFOREXECUTE = '';
    this.MESS_SUCCESSFUL = '';
    this.MESS_UNSUCCESSFUL = '';
    this.MESS_NAMEISEMPTY = '';
    this.MESS_USERSLISTISEMPTY = '';
    this.MESS_REPORTSLISTEMPTY = '';
    this.MESS_FORMATSLISTEMPTY = '';
    this.MESS_NOMOREREPORTSADD = '';

    // Labels and Titles
    this.TITLE_USERSOFROLE = '';
    this.LABEL_USER = '';
    this.LABEL_EMAIL = '';

    // Url-ek
    this.URL_DELETE = '';
    this.URL_USERLIST = '';     //az összes felhasználó választó inputhoz
    this.URL_USERSOFROLE = '';  //a "Riportot megkapják" akcióhoz
    this.URL_ROLEGROUPLIST = '';
    this.URL_REPORTLIST = '';
    this.URL_FORMATLIST = '';

    // Variables
    this.VAR_ROLENAME = '';
    this.VAR_PCKNAME = '';

    // Egyéb állandók
    this.ROLENAMEMASK = '';

    // Import változók
    this.EditorDialogId = '';
    this.EditorFormId = '';
    this.SelectedReports = [];
    this.SelectedFormats = [];

    //Törléshez
    this.confirmTitle = '';
    this.confirmDelete = '';
    this.labelId = '';
    this.labelName = '';
    this.labelDescription = '';
    this.labelYes = '';
    this.labelNo = '';
}
