//SCREEN-BOILERPLATE

//this boilerplate builds screens that are gonna be shown in the <div class='content'> tag of our main HTML.
//do not build app components with this boilerplate, only screens (reports)

define([
  // Application variable, always include it to have access to app methods.
  'app',

  //templates-loader: this loads templates async.
  'js/templates-loader',
  'backgrid',
  'moment',
    'modules/modal2',

  'backgrid/moment-cell',
  'js/jquery.clearsearch/jquery.clearsearch',

    'backgrid/infinator',
    'js/multiselect/virtual-select.min',
],
    function (app, T, Backgrid, moment, Modal) {
    var Screen = { Models: {}, Views: {}, Collections: {},};

    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {
            start: new moment().subtract(2, 'days').format('MM/DD/YYYY'),
            end: new moment().format('MM/DD/YYYY'),
            
            searchText: '',
            hasData: false,
            isLoading: 0,
            grid: null,            
            
            eventTypes: null,
            selected_eventTypes: [],
            ladles: null,
            selected_ladles: [],

            abnormalEventIds: [],
            moEventIds: [],

            abnormalEventSourceIds: [],
            moEventSourceIds: [],

            eventSources:null,
            selected_eventSources: [],
        },
        initialize: function () {
            this.fetchPickers({async: false});
        },
      
        fetchPickers: function (options) {
            var that = this,
                qp = new Core.Database.QueryParameters(),
                opt = _.extend({ async: true, }, options);

            var abs = [];
            var mo = [];

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.LAD.GetLadleTrackingEventsPickersWeb',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {

                                // Event Type Picker
                                that.set('eventTypes', _.map(resp.Table, function (obj) {   
                                    return {
                                        value: obj.Id,
                                        label: obj.Name,
                                        isAbnormalEvent: obj.isAbnormalEvent === 1 ? true : false,
                                        isMeltOrderChangeEvent: obj.isMeltOrderChangeEvent === 1 ? true : false,
                                    };
                                }));                                       
                                _.forEach(_.where(that.get('eventTypes'), { isAbnormalEvent: true }), function (obj,i) {
                                    abs[i] = obj.value;
                                });
                               
                                _.forEach(_.where(that.get('eventTypes'), { isMeltOrderChangeEvent: true }), function (obj, i) {
                                    mo[i] = obj.value;
                                });
                                that.set({
                                    selected_eventTypes: _.map(abs, function (obj) { return { value: obj.toString() } }),
                                    abnormalEventIds: abs,
                                    moEventIds: mo
                                });



                                // Ladle Picker
                                if (resp.Table1) {
                                    that.set('ladles', _.map(resp.Table1, function (obj) {
                                        return {
                                            value: obj.Id,
                                            label: obj.Name,
                                        };
                                    }));
                                }

                                // Event Source Picker
                                if (resp.Table2) {
                                    that.set('eventSources', _.map(resp.Table2, function (obj) {
                                        return {
                                            value: obj.Id,
                                            label: obj.Name,
                                            isAbnormalEvent: obj.isAbnormalEvent === 1 ? true : false,
                                            isMeltOrderChangeEvent: obj.isMeltOrderChangeEvent === 1 ? true : false,
                                        };
                                    }));

                                    abs = [];
                                    mo = [];

                                    _.forEach(_.where(that.get('eventSources'), { isAbnormalEvent: true }), function (obj, i) {
                                        abs[i] = obj.value;
                                    });

                                    _.forEach(_.where(that.get('eventSources'), { isMeltOrderChangeEvent: true }), function (obj, i) {
                                        mo[i] = obj.value;
                                    });
                                    that.set({
                                        selected_eventSources: _.map(abs, function (obj) { return { value: obj.toString() } }),
                                        abnormalEventSourceIds: abs,
                                        moEventSourceIds: mo
                                    });
                                }

                            
                            }
                          
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(new Error(resp.Message).stack);
                                else
                                    console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                            }
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: opt.async,
                },
                app.ConnectionStrings.app
            );

            return this;
        },


    });

    //the generate id method is called everytime a view is going to be shown by the router and returns and id that
    //is used by the router to store in cache (if it is cacheable) and to know the current shown view.
    //this is useful in case your view is reusable, and displays different data depending on url parameters 
    //(such as a catalog view, or a report that doesnt change in terms of UI but it does change in terms of data)
    //so you can always use the same view on the router but the cache can tell which view is which by using differents ids.
    Screen.generateID = function (viewParams) {
        try {
            //if the viewparams change the view id, then evaluate the viewparams here
            //and return the appropiate id.refreshbtn
            return 'ladle-tracking-events';
        } catch (Error) { }
    }

    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: 'ladle-tracking-events'
        , id: 'ladle-tracking-events'
        , title: 'Ladle Tracking Events'

        //default not cacheable, change this if you want the view to be cacheable
        // if the view is set as cacheable should also have a _refresh method to reset the view without erasing the DOM.
        , isCacheable: false
        , events: function () {
            return {                
                'keypress #searchTbx': this.searchTbx_keypress,  
                'keydown #search': this.search_keydown,
                'click #abnormalEventsBtn': this.abnormalEventsBtn_click,
                'click #moChangeEventsBtn': this.moChangeEventsBtn_click,
                "click .btn-export-to-excel": this.exportToExcel,
                
            };
        }
        , bindings: 'data-bind'
        , setIdNull: false
        , itemsColl: null
        , searchTbx: null
        , initialize: function () {
            this.options.state = app.view_states.loading;
            this.options.onappend = (_.isFunction(this.options.onappend)) ? this.options.onappend : function () { };
           
            this.model = new Screen.Models.Main();
            this.itemsColl = new Screen.Collections.Items();
            this.bindEvents();
            
          
        }
        
        , exportToExcel: function () {
            var that = this,
                params = this.model.toJSON();

            var params = [
                { Name: '@start', Type: 'DATETIME', Value: params.start },
                { Name: '@end', Type: 'DATETIME', Value: params.end },
                { Name: '@Search', Type: 'VARCHAR', Value: params.searchText != '' ? params.searchText : null, },
               

            ];
            

            var QP = new QueryParameters();

            _.each(params, function (qpParams) {
                QP.Add(qpParams.Name, qpParams.Type, qpParams.Value);
            });

            //Event Types layout data xml parameter
            var eventTypes = this.model.get('selected_eventTypes');

            QP.Add(
                'LayoutEventTypes',
                'XML',
                app.jsonArrayToXml(
                    eventTypes,
                    [
                        'value',
                    ]
                )
            );

            //Ladles layout data xml parameter
            var ladles = this.model.get('selected_ladles');

            QP.Add(
                'LayoutEventTypes',
                'XML',
                app.jsonArrayToXml(
                    ladles,
                    [
                        'value',
                    ]
                )
            );

            var data = {
                Data: [],
                ConnectionStringName: 'APP',
                ExportMethod: 3,
                FileName: 'Ladle Tracking Events',
                TemplateFileFullPath: 'generic.xls',
                SQLDataSources: [
                    {
                        Name: 'data',
                        DatabaseParameters: {
                            DBEngine: 'SQLSERVER',
                            Procedure: app.DatabaseNames.MES + '.LAD.GetLadleTrackingEventsWeb',
                            QueryParameters: QP,
                        },
                    },
                ]
            };

            /* -------------------------------------------------------- 1st Table ------------------------------------------------------------ */
            data.Data.push({
                SheetName: 'Data',
                RowsData: [{
                    CellsData:
                        [
                            { Column: 'A', Value: 'Heat' },
                            { Column: 'B', Value: 'Ladle' },
                            { Column: 'C', Value: 'Datetime' },
                            { Column: 'D', Value: 'Event' },
                            { Column: 'E', Value: 'Source' },
                            { Column: 'F', Value: 'Melt Order' },
                            { Column: 'G', Value: 'Grade Name' },
                            { Column: 'H', Value: 'Description' },
                            { Column: 'I', Value: 'Comments' },
                           


                        ],
                }],
                StartRowIndex: 1,
            });

            data.Data.push({
                SheetName: 'Data',
                RowsData: [],
                StartRowIndex: 2,
                DataSourceName: 'data',
                DataSourceTableIndex: 0,
                SQLCellsData:
                    [
                        { ExcelColumnName: 'A', SQLDataColumnName: 'HeatNumber', DataType: 'String' },
                        { ExcelColumnName: 'B', SQLDataColumnName: 'LadleID', DataType: 'String' },
                        { ExcelColumnName: 'C', SQLDataColumnName: 'DatetimeLocal', DataType: 'String' },
                        { ExcelColumnName: 'D', SQLDataColumnName: 'LadleEventName', DataType: 'String' },
                        { ExcelColumnName: 'E', SQLDataColumnName: 'EventSource', DataType: 'String' },
                        { ExcelColumnName: 'F', SQLDataColumnName: 'MeltOrder', DataType: 'String' },
                        { ExcelColumnName: 'G', SQLDataColumnName: 'GradeName', DataType: 'String' },
                        { ExcelColumnName: 'H', SQLDataColumnName: 'Description', DataType: 'String' },
                        { ExcelColumnName: 'I', SQLDataColumnName: 'Comments', DataType: 'String' },
                      

                    ],
            });

            Core.Export.Excel(
                data,
                function (resp) {
                    try {
                        if ((resp) && (resp.Success == true) && (resp.Data)) {
                            location.href = app.foldersRoot + '/excel/' + resp.Data;

                        }
                        else {
                            if ((resp) && (resp.Message))
                                console.error(resp.Message);
                            else
                                console.error('Server response not valid.');
                        }
                    }
                    catch (Error) { console.error(Error); }
                    that.model.setExportButtonExporting(false);
                },
                function (resp) {
                    that.model.refresheventTypes();
                    that.model.setExportButtonExporting(false);
                    console.error(resp);
                }
            );
        }

        , search_keydown: function (e) {
            if (e.which == 13) {
                $("#search").blur();
                this.refresh(null);
            }
        }

        , abnormalEventsBtn_click: function () {
            var that = this;
            //document.querySelector('#event-types-picker-multi-select').toggleSelectAll(false); //remove all selected values
            document.querySelector('#event-types-picker-multi-select').setValue(that.model.get('abnormalEventIds'));
            document.querySelector('#event-source-picker-multi-select').setValue(that.model.get('abnormalEventSourceIds'));
        
        }
        , moChangeEventsBtn_click: function (){
            var that = this;
            document.querySelector('#event-types-picker-multi-select').setValue(that.model.get('moEventIds'));
            document.querySelector('#event-source-picker-multi-select').setValue(that.model.get('moEventSourceIds'));
        }
        ,multiselect_picker_eventTypes: function(){
            var that = this;

            //--------------------------------
            //-------- EVENT PICKER ------
            //--------------------------------
            var eventTypesPickerVirtualSelect = new   VirtualSelect.init({
                    ele: '#event-types-picker-multi-select',
                    options: that.model.get('eventTypes'),                             
                    multiple: true,
                    search: true,
                    placeholder: 'Select Event Types',
                    showSelectedOptionsFirst: true,
                    selectedValue: that.model.get('abnormalEventIds'),
            });         
            document.querySelector('#event-types-picker-multi-select').addEventListener('change', function() {
                var eventTypes = [];

                that.model.set({selected_eventTypes: []});
                _.each(this.value,function(obj){
                    eventTypes.push({value: obj});
                });
                            
                that.model.set({selected_eventTypes: eventTypes});
                that.refresh(null);
            });
        }

        , multiselect_picker_ladles: function () {
            var that = this;

            //--------------------------------
            //-------- EVENT PICKER ------
            //--------------------------------
            var LadlesPickerVirtualSelect = new VirtualSelect.init({
                ele: '#ladles-picker-multi-select',
                options: that.model.get('ladles'),
                multiple: true,
                search: true,
                placeholder: 'Select Ladles',
                showSelectedOptionsFirst: true,
            });
            document.querySelector('#ladles-picker-multi-select').addEventListener('change', function () {
                var ladles = [];

                that.model.set({ selected_ladles: [] });
                _.each(this.value, function (obj) {
                    ladles.push({ value: obj });
                });

                that.model.set({ selected_ladles: ladles });
                that.refresh();
            });
        }

        , multiselect_picker_event_source: function () {
            var that = this;

            //--------------------------------
            //-------- EVENT PICKER ------
            //--------------------------------
            var eventSourcesPickerVirtualSelect = new VirtualSelect.init({
                ele: '#event-source-picker-multi-select',
                options: that.model.get('eventSources'),
                multiple: true,
                search: true,
                placeholder: 'Select Event Source',
                showSelectedOptionsFirst: true,
                selectedValue: that.model.get('abnormalEventSourceIds'),
            });
            document.querySelector('#event-source-picker-multi-select').addEventListener('change', function () {
                var eventSources = [];

                that.model.set({ selected_eventSources: [] });
                _.each(this.value, function (obj) {
                    eventSources.push({ value: obj });
                });

                that.model.set({ selected_eventSources: eventSources });
                that.refresh(null);
            });
        }


        , multiselectPickersConfiguration: function(){
            this.multiselect_picker_eventTypes();   
            this.multiselect_picker_ladles();
            this.multiselect_picker_event_source();
            
        }

        , bindEvents: function () {
            this.listenTo(this.model, 'change:start change:end', this.refresh);   
            this.listenTo(this.itemsColl, 'fetch', this.itemsColl_fetch);
            this.listenTo(this.model, 'change:searchText', this.searchChanged);
        }
        , searchChanged: _.debounce(function (a, b, c) {
            this.refresh();
        }, 300)


        , render: function (container, viewParams) {
            var that = this;
            var thatContainer = (this.options.container) ? this.options.container : container;
            this.options.container = thatContainer;
            //the screens have a custompath, so it has to be specified in the customPath variable that is
            //then sent to the template loader.
            var customPath = '/app/custom-screens/' + this.template + '/';

            T.render.call(
                this,
                this.template,
                function (tmp) {

                    //getInternationalizationData
                    if (!that.options.i18n) that.options.i18n = {};
                    
                    app.getI18NJed(
                        that,
                        that.template,
                        function (i18nJED) {
                            //storing internationalization data
                            that.options.i18n[that.template] = i18nJED;
                            that.$el.html(tmp());
                            that.applyBindings();
                            that.append(thatContainer, that.$el);

                            that.multiselectPickersConfiguration();
                     

                            var grid = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed production-table',
                                columns: [
                                    {
                                        name: 'HeatNumber',
                                        label: 'Heat',
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },
                                    {
                                        name: 'LadleID',
                                        label: 'Ladle',
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },
                                    {
                                        name: 'DatetimeLocal',
                                        label: 'Datetime',
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },
                                    {
                                        name: 'LadleEventName',
                                        label: 'Ladle Event',
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),

                                    },
                                     {
                                        name: 'EventSource',
                                        label: 'Event Source',
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },
                                  
                                 
                                    {
                                        name: 'MeltOrder',
                                        label: app.translate(that, 'item_melt_order_col_label'),
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },
                                    {
                                        name: 'GradeName',
                                        label: 'Grade',
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },
                                    {
                                        name: 'Description',
                                        label: 'Description',
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },
                                    {
                                        name: 'Comments',
                                        label: 'Comments',
                                        editable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },
                                   
                                ],
                                collection: that.itemsColl,
                                footer: Backgrid.Extension.Infinator.extend({
                                    scrollToTop: false,
                                }),
                            });

                            that.model.set({ grid: grid });
                            that.$el.find('.items-grid-container').append(grid.render().el);

                            that.$el.find('.input-date').datepicker();

                            // set view parameters as model parameters
                            //Set model with view params here to prevent changes on the model when the view bindings are applied.
                            var fixedParams = _.extend({}, viewParams);

                            if (fixedParams.start)
                                fixedParams.start = new moment(fixedParams.start, 'YYYYMMDD').format('MM/DD/YYYY');
                            if (fixedParams.end)
                                fixedParams.end = new moment(fixedParams.end, 'YYYYMMDD').format('MM/DD/YYYY');
                        


                            that.model.set(fixedParams);

                            // refresh collection
                            that.refresh();
                        },
                        true,
                        customPath
                    );
                },
                customPath
            );
        }, 

        refresh: function () {
            try {
                // reload collection 
                this.itemsColl.fetch({
                    selected_eventSources: this.model.get('selected_eventSources'),
                    selected_eventTypes: this.model.get('selected_eventTypes'),
                    selected_ladles: this.model.get('selected_ladles'),
                    searchText: this.model.get('searchText'),
                    start: this.model.get('start'),
                    end: this.model.get('end'),
                    refresh: true,
                });
                this.UpdateURL();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        }
        , itemsColl_fetch: function (coll, resp) {
            try {
                var that = this;
                setTimeout(
                    function () {
                        that.model.set({
                            hasData: (that.itemsColl.length > 0),
                            isLoading: false,
                        });
                    },
                    100
                );                

            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        }

     

        , UpdateURL: function () {
            try {
                var params = this.model.toJSON();
                app.router.navigate(
                    app.router.resolveURL(
                        app.router.currentModule,
                        _.extend(
                            {},
                            params,
                            {
                                start: new moment(params.start, 'MM/DD/YYYY').format('YYYYMMDD'),
                                end: new moment(params.end, 'MM/DD/YYYY').format('YYYYMMDD'),
                            }
                        ),
                        false
                    ),
                    { trigger: false, }
                );
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },           


        hasScrollBar: function () {
            var element = document.getElementById("grid-ladle-tracking-events");
            if (element) {
                var scrollBarHeight = element.scrollHeight;

                if (parseFloat(scrollBarHeight) > window.innerHeight) {
                    return true;
                }
                else
                    return false;
            }
            
        },




        // Common Functions

        append: function (container, el) {
            el = (el != null && el != undefined) ? el : this.$el;

            if (this.options.state == app.view_states.loading
                || this.options.state == app.view_states.shown) {
                //appending view to the main container and set state to shown

                this.options.state = app.view_states.shown;
                container.append(el);

                this.options.onappend(this);
            }

            if (this.options.state == app.view_states.hidden) {
                //append and remain hidden
                container.append(el);
            }

            if (this.options.state == app.view_states.closed) {
                //return without appending.
                return;
            }
        },

        bindViewScopedEvents: function () {
            var that = this;
        },
        unbindViewScopedEvents: function () {

        },
        close: function () {
            this.options.state = app.view_states.closed;

            this.remove();
            this.unbindViewScopedEvents();
            this.unbind();
        },
        show: function () {
            this.options.state = app.view_states.shown;

            this.bindEvents();
            this.$el.show();
        },
        hide: function () {
            this.options.state = app.view_states.hidden;

            this.$el.hide();
            this.unbind();
            this.stopListening();
        },
        preRender: function () {
            app.models.subnavbar.set('subnavbar', false);
        },
        reRender: function (viewParams) {
            try {
                this.refresh(null);
            } catch (Error) { }
        },


    });

        

    Screen.Collections.Items = Backbone.Collection.extend({
        isFetching: false,
        currentPage: 1,
        pageSize: 100,


        fixedParameters: [],

        getGridId: function () {
            return 'grid-ladle-tracking-events';
        },

        fetch: function (params) {
            var that = this,
                qp = new Core.Database.QueryParameters(),
                options = params ? _.clone(params) : {};

            
            if (options.refresh) {
                this.resetPagination(true);

                this.fixedParameters = [
                    { Name: '@Search', Type: 'VARCHAR', Value: params.searchText != '' ? params.searchText : null, },
                    { Name: '@Start', Type: 'DATE', Value: params.start },       
                    { Name: '@End', Type: 'DATE', Value: params.end },        
                ];
                //Event Types layout data xml parameter
                var eventTypes = [];
                var alleventTypesSelected = document.querySelector('#event-types-picker-multi-select').isAllSelected();
                if (!alleventTypesSelected) eventTypes = params.selected_eventTypes;

                this.fixedParameters.push({
                    Name: '@LayoutEventTypes',
                    Type: 'XML',
                    Value: app.jsonArrayToXml(eventTypes, ['value']),
                });

                //Ladles layout data xml parameter
                var ladles = [];
                var allladlesSelected = document.querySelector('#ladles-picker-multi-select').isAllSelected();
                if (!allladlesSelected) ladles = params.selected_ladles;

                this.fixedParameters.push({
                    Name: '@LayoutLadles',
                    Type: 'XML',
                    Value: app.jsonArrayToXml(ladles, ['value']),
                });

                //Event Sources layout data xml parameter
                var eventSources = [];
                var alleventSourcesSelected = document.querySelector('#event-source-picker-multi-select').isAllSelected();
                if (!alleventSourcesSelected) eventSources = params.selected_eventSources;

                this.fixedParameters.push({
                    Name: '@LayoutEventSources',
                    Type: 'XML',
                    Value: app.jsonArrayToXml(eventSources, ['value']),
                });



            }
            this.isFetching = true;

            _.each(this.fixedParameters, function (qpParams) {
                qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
            });

            if (!options.refresh) {
                qp.Add('@fromRow', 'INT', (this.currentPage - 1) * this.pageSize + 1);
                qp.Add('@rowsToFetch', 'INT', this.pageSize -1);
            } else {
                qp.Add('@fromRow', 'INT', 0);
                qp.Add('@toRow', 'INT', this.currentPage * this.pageSize);
                qp.Add('@rowsToFetch', 'INT', this.pageSize);
            }
            Core.Json.CallProcedure(
                 app.DatabaseNames.MES + '.LAD.GetLadleTrackingEventsWeb',
                 qp,
                 {
                     onSuccess: function (resp) {
                         try {
                             if ((resp) && (resp.Table)) {
                                 var newColl = resp.Table;
                                 var method = (options.refresh) ? 'set' : 'add';

                                 that[method](newColl);
                                 that.trigger('fetch', that, newColl);

                                 if (newColl.length == 0 && method == 'add')
                                     that.currentPage--;


                                 that.isFetching = false;

                             }
                             else {
                                 if ((resp) && (resp.Message)) {
                                     console.error(new Error(resp.Message).stack);
                                     app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 5000, });
                                 }
                                 else {
                                     app.views.topMessages.showMessage('SERVER RESPONSE NOT VALID', { stay: 5000, });
                                     console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                 }
                             }
                         }
                         catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                     },
                     onFailure: function (resp) {
                         console.error(resp);
                     },
                     Secured: true,
                     Async: true,
                 },
                 app.ConnectionStrings.app
            );
            return this;
        },
        getNextPage: function (options) {
            if (!this.isFetching) {
                this.currentPage++;
                options = (_.isObject(options)) ? options : {};
                this.fetch(options);
            }
        },
        resetPagination: function (force) {
            if (!this.isFetching || force == true) {
                this.currentPage = 1;
            } else {
                _.delay(this.resetPagination, 100);
            }
        },

    });

   
    
    // Required, return the module for AMD compliance.
    return Screen;

});