/**
 * Base.DataTable 1.0
 *
 * Requiere
 *     Base 1.0
 *     Base.Filter 1.0
 */
$(function() {
    $.extend(Base, {
        DataTable : {

            _language: {
               "sProcessing":     '<div class="blockui-message"><span class="spinner-border spinner-border-sm align-middle ms-2 text-primary"></span> Cargando...</div>',
               "sLengthMenu":     "_MENU_",
               "sZeroRecords":    "Sin resultados",
               "sEmptyTable":     "Sin datos",
               "sInfo":           "Resultado _START_ - _END_ de _TOTAL_",
               "sInfoEmpty":      "No hay registros",
               "sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",
               "sInfoPostFix":    "",
               "sSearch":         "Buscar:",
               "sUrl":            "",
               "sInfoThousands":  ",",
               "sLoadingRecords": "Cargando...",
               "oAria": {
                   "sSortAscending":  ": Activar para ordenar la columna de manera ascendente",
                   "sSortDescending": ": Activar para ordenar la columna de manera descendente"
                }
            },

            createSimpleAjax: function (selector, options) {

                var _i18n = {
                    actionColunmLabel: 'Actions',
                    language: {
                        "lengthMenu":     "Show _MENU_ entries"
                    }
                };

                _i18n = $.extend(true, _i18n, Base.i18n.datatable);

                if (options._i18n !== undefined && options._i18n != null) {
                    _i18n = $.extend(true, _i18n, options._i18n);
                }

                var defaultOptions = {
                    deferLoading: (Base.DashboardFilter.isFilterReady(selector)) ? null : 0,
                    responsive: true,
                    serverSide: true,
                    processing: true,
                    paging: false,
                    pageLength: 10,
                    lengthMenu: [10, 25, 50, 75, 100],
                    language: this._language,
                    columnDefs: [],
                    onRowClick: null,
                    rowClickMode: 'FULL',
                    autoWidth: true,
                    sort: false,
                    searching: false,
                    myDrawCallback: null,
                    customData: {},
                    drawCallback: function (oSettings) {
                        if(options.myDrawCallback != undefined && options.myDrawCallback != null && $.isFunction(options.myDrawCallback)) {

                            return options.myDrawCallback(oSettings);
                        }
                    },
                    ajax: {
                        url: options.url,
                        type: "POST",
                        dataType: "json",
                        async: false,
                        contentType: 'application/json; charset=utf-8',
                        dataSrc: function (data) {

                            return data.content;
                        },
                        data: function (data, table) {

                            var sort = {};

                            var customData = {};

                            if (options.customData != undefined && options.customData != null && $.isFunction(options.customData)) {

                                customData = options.customData();
                            }
                            else if(options.customData != undefined && options.customData != null ){

                                customData = options.customData;
                            }

                            var myData = {
                                draw: data.draw,
                                page: 0,
                                size: 1,
                                search: null,
                                sort: sort,
                                dashboardFilter: Base.DashboardFilter.buildFiltersRequest(selector),
                                data: customData
                            };

                            return JSON.stringify(myData);
                        }
                    },
                };

                var _columnActions = function (options) {

                    var defaultOptions = {
                        column: {
                            data: "id",
                            title: _i18n.actionColunmLabel,
                            className: "list-table-columns-actions",
                            width: "15%"
                        },
                        columnDef: {
                            targets: -1,
                            orderable: false,
                            render: function (data, type, row, meta) {

                                if (options.buttons != undefined && options.buttons != null && $.isFunction(options.buttons)) {
                                    return options.buttons(data, type, row, meta);
                                }

                                return "";
                            }
                        }
                    };

                    return $.extend(true, defaultOptions, options);
                };

                var finallyOptions = $.extend(true, defaultOptions, options);

                if (options.columnActions !== undefined && options.columnActions != null) {

                    var columnActions = _columnActions(options.columnActions);

                    finallyOptions.columns.push(columnActions.column);
                    finallyOptions.columnDefs.push(columnActions.columnDef);
                }
                Base.DataTable._globalActionRow(selector, finallyOptions);

                return $(selector).DataTable(finallyOptions);
            },

            createStaticTable: function (selector, options) {

                var _i18n = {
                    actionColunmLabel: 'Actions',
                    language: {
                        "lengthMenu":     "Show _MENU_ entries"
                    }
                };

                _i18n = $.extend(true, _i18n, Base.i18n.datatable);

                if (options._i18n !== undefined && options._i18n != null) {
                    _i18n = $.extend(true, _i18n, options._i18n);
                }

                var defaultOptions = {
                    responsive: true,
                    pagingType: 'none',
                    serverSide: false,
                    processing: false,
                    paging: false,
                    info: false,
                    language: this._language,
                    columnDefs: [],
                    onRowClick: null,
                    rowClickMode: 'FULL',
                    autoWidth: true,
                    sort: false,
                    searching: false,
                    myDrawCallback: null,
                    drawCallback: function (oSettings) {
                        if(options.myDrawCallback != undefined && options.myDrawCallback != null && $.isFunction(options.myDrawCallback)) {

                            return options.myDrawCallback(oSettings);
                        }
                    }
                };

                var _columnActions = function (options) {

                    var defaultOptions = {
                        column: {
                            title: _i18n.actionColunmLabel,
                            className: "list-table-columns-actions",
                            width: "15%"
                        },
                        columnDef: {
                            targets: -1,
                            orderable: false,
                            render: function (data, type, row, meta) {

                                if (options.buttons != undefined && options.buttons != null && $.isFunction(options.buttons)) {
                                    return options.buttons(data, type, row, meta);
                                }


                                return "";
                            }
                        }
                    };

                    return $.extend(true, defaultOptions, options);
                };

                var finallyOptions = $.extend(true, defaultOptions, options);

                if (options.columnActions !== undefined && options.columnActions != null) {

                    var columnActions = _columnActions(options.columnActions);

                    finallyOptions.columns.push(columnActions.column);
                    finallyOptions.columnDefs.push(columnActions.columnDef);
                }
                Base.DataTable._globalActionRow(selector, finallyOptions);

                return $(selector).DataTable(finallyOptions);
            },

            create: function (selector, options) {
                var _i18n = {
                    actionColunmLabel: 'Actions',
                    language: {
                        "lengthMenu":  "Show _MENU_ entries"
                    }
                };

                _i18n = $.extend(true, _i18n, Base.i18n.datatable);

                if (options._i18n !== undefined && options._i18n != null) {
                    _i18n = $.extend(true, _i18n, options._i18n);
                }

                var defaultOptions = {
                    deferLoading: (Base.DashboardFilter.isFilterReady(selector)) ? null : 0,
                    responsive: true,
                    serverSide: true,
                    processing: true,
                    paging: true,
                    pageLength: 10,
                    lengthMenu: [10, 25, 50, 75, 100],
                    language: this._language,
                    columnDefs: [],
                    onRowClick: null,
                    rowClickMode: null,
                    autoWidth: true,
                    sort: false,
                    searching: false,
                    myDrawCallback: null,
                    customData: null,
                    drawCallback: function (oSettings) {

                        if(options.myDrawCallback != undefined && options.myDrawCallback != null && $.isFunction(options.myDrawCallback)) {

                            return options.myDrawCallback(oSettings);
                        }
                    },
                    ajax: {
                        url: options.url,
                        type: "POST",
                        dataType: "json",
                        async: false,
                        contentType: 'application/json; charset=utf-8',
                        dataSrc: function (data) {

                            return data.content;
                        },
                        data: function (data, table) {

                            var sort = {};

                            if (defaultOptions.sort) {

                                var order = [];
                                for (var i = 0; i < data.order.length; i++) {

                                    var columnSort = (typeof data.columns[data.order[i].column].data == 'string')
                                        ? data.columns[data.order[i].column].data
                                        : data.columns[data.order[i].column].data.sort;
                                    order.push({
                                        column: columnSort,
                                        direction: data.order[i].dir
                                    })
                                }

                                sort = {
                                    orderList: order
                                }
                            }

                            var customData = {};

                            if (options.customData != undefined && options.customData != null && $.isFunction(options.customData)) {

                                customData = options.customData();
                            }
                            else if(options.customData != undefined && options.customData != null ){

                                customData = options.customData;
                            }

                            var myData = {
                                draw: data.draw,
                                page: $(selector).DataTable().page.info().page,
                                size: data.length,
                                search: data.search.value,
                                sort: sort,
                                dashboardFilter: Base.DashboardFilter.buildFiltersRequest(selector),
                                data: customData
                            };

                            return JSON.stringify(myData);
                        }
                    },
                };

                var _columnActions = function (options) {

                    var defaultOptions = {
                        column: {
                            data: "id",
                            title: _i18n.actionColunmLabel,
                            className: "list-table-columns-actions",
                            width: "15%"
                        },
                        columnDef: {
                            targets: -1,
                            orderable: false,
                            render: function (data, type, row, meta) {

                                if (options.buttons != undefined && options.buttons != null && $.isFunction(options.buttons)) {
                                    return options.buttons(data, type, row, meta);
                                }

                                return "";
                            }
                        }
                    };

                    return $.extend(true, defaultOptions, options);
                };

                var finallyOptions = $.extend(true, defaultOptions, options);

                if (options.columnActions !== undefined && options.columnActions != null) {

                    var columnActions = _columnActions(options.columnActions);

                    finallyOptions.columns.push(columnActions.column);
                    finallyOptions.columnDefs.push(columnActions.columnDef);
                }
                Base.DataTable._globalActionRow(selector, finallyOptions);

                return $(selector).DataTable(finallyOptions);
            },

            _globalActionRow: function(selector, options){

                if ((options.onRowClick == undefined || options.onRowClick == null)
                       && !$.isFunction(options.onRowClick)) {

                    return;
                }

                var trSelector = '';
                var trSelector1 = '';
                var trSelector2 = '';

                //No click en la primera columna
                if(options.rowClickMode == 'SKIP-FIRST'){
                    trSelector1 += 'tbody tr td:first-child';
                }
                //No click en la ultima columna (o esta activado las options)
                if(options.rowClickMode == 'SKIP-LAST'
                    || (options.columnActions !== undefined && options.columnActions != null)){
                    trSelector2 = 'tbody tr td:last-child';
                }
                if(trSelector1 != ""){
                  trSelector1 += ", ";
                }
                trSelector = 'td:not(' + trSelector1 + trSelector2 + ')';

                $(selector).on('click', trSelector, function () {

                    var data = $(selector).DataTable().row( this ).data();

                        return options.onRowClick(data);
                } );
            },

            _qxDataTable : function (table) {

                return {

                    ver : function () {

                        console.log("Base.DataTable 1.0");
                        console.log("Requiere: Base 1.0; Base.Filter 1.0");
                    },

                    reload: function () {

                        $(table).DataTable().ajax.reload();
                    },

                    deleteRow: function (idx, callback, redraw) {

                        $(table).dataTable().fnDeleteRow(idx, callback, redraw);
                        $(table).DataTable().rows().invalidate();
                    }
                 }
            }
        }
    });

    $.fn.QxDataTable = function () {

        var table = this;

        return Base.DataTable._qxDataTable(table);
    }
    
}); 