/**
 * BaseJS 1.0
 */
$(function () {
    Base = {

        locale: {
            language: 'es',
        },

        i18n: {
            datatable: {},
            buttons: {},
            modal: {},
            date: {},
            box: {},
            print: {},
            kanban: {},
            typedjs: {},
            touchspin: {},
            loading: {}
        },

        month: {
            fullNames: ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio",
                "Agosto", "Septiembre", "Octubre", "Noviembre", "Deciembre"],
            acronyms: ["Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dec"]
        },

        daysOfWeek: {
            fullNames: ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"],
            acronyms: ["Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sa"]
        },

        TempCode: {},

        initComponents: function () {

            //https://momentjs.com/docs/#/i18n/
            moment.locale(Base.locale.language);
            moment.updateLocale('es', {
                months: Base.month.fullNames,
                monthsShort: Base.month.acronyms,
                weekdays: Base.daysOfWeek.fullNames,
                weekdaysShort: Base.daysOfWeek.acronyms,
                weekdaysMin: Base.daysOfWeek.acronyms
            });

            Base.Select.create('.base-select-mth8', {});
            Base.Date.create('.base-date-mth8', {});

            $(document).on('select2:open', () => {
                let allFound = document.querySelectorAll('.select2-container--open .select2-search__field');
                allFound[allFound.length - 1].focus();
            });

            //Gedux.markMenuActive();
            Base._deleteConfirmSimple();
          //  Gedux.hiddenToolMenu();
            //Base._makeButtons();
        },

        showFlashMessageFromServer: function (geduxFlashMessages) {

            if (undefined != geduxFlashMessages && null != geduxFlashMessages) {

                geduxFlashMessages.forEach(function (object, idx) {

                    let typeMessage = object.showType;
                    let classMessage = object.classMessage;
                    let message = object.message;

                    if (typeMessage == 'SIMPLE') {
                        Base.Message.flash(message, classMessage);
                    } else {
                        alert("Mensaje Flash " + typeMessage + " NO Soportado");
                    }
                });
            }
        },

        _loadingGlobal: null,

        isSecurityAccessFor: function (chkRoles) {

            if (chkRoles == 'ALL') {
                return true;
            }

            if (app.user.roles.indexOf('ROLE_ROOT') >= 0) {
                return true;
            }

            if (null == chkRoles || chkRoles == undefined) {

                return false;
            }

            if (Array.isArray(chkRoles)) {

                for (var i = 0; i < chkRoles.length; i++) {

                    if (app.user.roles.indexOf(chkRoles[i]) > 0) {

                        return true;
                    }
                }

            } else {
                return (app.user.roles.indexOf(chkRoles) >= 0);
            }

            return false;
        },

        guid: function () {
            return Base._s4() + Base._s4() + '-' + Base._s4() + '-' + Base._s4() + '-' +
                Base._s4() + '-' + Base._s4() + Base._s4() + Base._s4();
        },

        localeConfig: function (options) {

            Base.locale = $.extend(true, Base.locale, options);
        },

        loadLanguage: function (baseUrlScript, reload) {

            $.cookie.json = true;

            if (reload || $.cookie('base_language') == undefined) {
                Base._readLanguage(baseUrlScript);
            } else {
                Base.i18n = $.cookie('base_language');
            }
        },
        downloadFile: function (url, fileName) {

            $.ajax({
                url: url,
                cache: false,
                xhr: function () {
                    var xhr = new XMLHttpRequest();
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState == 2) {
                            if (xhr.status == 200) {
                                xhr.responseType = "blob";
                            } else {
                                xhr.responseType = "text";
                            }
                        }
                    };
                    return xhr;
                },
                success: function (data) {
                    //Convert the Byte Data to BLOB object.
                    var blob = new Blob([data], {type: "application/octetstream"});

                    //Check the Browser type and download the File.
                    var isIE = false || !!document.documentMode;
                    if (isIE) {
                        window.navigator.msSaveBlob(blob, fileName);
                    } else {
                        console.log("entrooo a descargar")
                        console.log("url", url)
                        console.log("fileName", fileName)
                        var url = window.URL || window.webkitURL;
                        link = url.createObjectURL(blob);
                        var a = $("<a />");
                        a.attr("download", fileName);
                        a.attr("href", link);
                        $("body").append(a);
                        a[0].click();
                        $("body").remove(a);
                    }
                }
            });
        },
        TempCode: {},
        ajax: function (url, data, callback, config) {

            if (typeof callback != 'function') {

                config = callback;
            } else if (typeof config == 'undefined') {
                config = {};
            }

            var default_config = {
                url: url,
                async: false,
                type: 'POST',
                contentType: 'application/json; charset=UTF-8',
                dataType: 'json',
                data: JSON.stringify(data),
                error: function (response, statusText) {
                    return false;
                },
                dataFilter: function (data, type) {

                    return data;
                },
                success: callback
            };

            $().extend(true, default_config, config);

            $.ajax(default_config);
        },

        _readLanguage: function (baseUrlScript) {

            $.ajax({
                url: baseUrlScript + "/i18n/" + Base.locale.language + ".json",
                dataType: "json",
                cache: true,

            }).done(function (data) {

                Base.i18n = $.extend(true, Base.i18n, data);
                $.cookie("base_language", Base.i18n, {expires: 7, path: '/'});

            }).fail(function (jqXHR, textStatus, errorThrown) {

                console.log(errorThrown);
            });
        },

        _s4: function () {
            return Math.floor((1 + Math.random()) * 0x10000)
                .toString(16)
                .substring(1);
        },

        _deleteConfirmSimple: function () {

            $.each($('.btn_simple_delete_confirm'), function (i, obj) {

                var url = $(obj).attr('uriAction');
                var messageDel = $(obj).attr('messageDel');
                if (messageDel == undefined || messageDel == "") {
                    messageDel = "¿Desea realmente eliminar el elemento?";
                }

                $(obj).click(function (e) {
                    e.preventDefault();

                    Base.Alert.custom({
                        title: "Confirmado eliminación",
                        text: messageDel,
                        type: "question",
                        confirmButtonText: "Acepto",
                        showCancelButton: true,
                        cancelButtonText: "Cancelar",
                        callBackThen: function (result) {

                            if (result.isConfirmed) {
                                window.location = url;
                            }
                        }
                    });
                });
            });
        },

        _makeButtons: function () {

            $('[data-toggle=confirmation-submit]').confirmation({
                rootSelector: '[data-toggle=confirmation-submit]',
                // other options
            });

            $('[data-toggle=confirmation-delete]').confirmation({
                rootSelector: '[data-toggle=confirmation-delete]',
                // other options
            });
        }

    };
});

/** TO ADD COMPONENT IN OTHER FILE.JS
 * Base.Component [ver] (Example: 1.0)
 *
 * Requiere
 *     Base [ver] (Example: 1.0)
 *     ...
 */
// $(function() {
//     $.extend(Base, {
//         Component = {
//              create: function (selector, options) {},
//
//             _qxComponent : function (object) {
//
//                 return {
//
//                     ver : function () {
//
//                          console.log("Base.Component 1.0");
//                          console.log("Requiere: Base 1.0; Base.OtherComponent 1.0");
//                     },
//
//                     otherfunction: function (param1, param2) {
//
//                     }
//                 }
//             }
//         },
//     });
//
//     //Para hacer llamadas a funciones extendidas: $(selector).Component().function() 
//     $.fn.QxComponent = function () {
//
//        var object = this;
//
//        return Base.Component.qxComponent(object);
//     }
// });