//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/infinator',
  'backgrid/moment-cell',
  'backgrid/grouped-columns',
  
  "js/jquery.floatThead/jquery.floatThead",
],
function (app, T, Backgrid, moment,Modal) {

    var Screen = { Models: {}, Views: {}, Collections: {} }

    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {
            start: new moment().format('YYYY-MM-DD'),
            hasData: false,
            isLoading: false,
            
            filterGroup: 'NONE',
            grid: [],
            gridDates: [],
            arrayDates: [],
            columns: [],
            allData: [],
            // Fill Type 1
            dateAutoFill: null,
            isChecked: false,
            
            // Fill Type 2
            radio_none: false,            
            radio_all: false,
            radio_week1: false,
            radio_week2: false,
            radio_week3: false,
            radio_week4: false,
            radio_week5: false,

            radio_checked:null,
            radio_option: 'radio_none',
            
            // Fill Type 3
            currentDate: null,
            currentHour: null, 
            currentMWHLimit: null,

            //Detect if a cell has changed
            cellChanged: false,
        },
        computeds: {
            start$: {
                deps: ['start'],
                get: function (value) {
                    return value;
                },
                set: function (value) {
                    return { start: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                },
            },
        },

        
        fetch: function (params) {
            var that = this;
                qp = new Core.Database.QueryParameters();
            this.fixedParameters = [
                { Name: '@start', Type: 'DATE', Value: params.start, },
            ];
            _.each(this.fixedParameters, function (qpParams) {
                qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
            });
            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.PWR.GetPowerForecast',
                qp,
                {
                    onSuccess: function (resp) {
                        try {

                            if ((resp) && (resp.Table)) {
                               // var newColl = _.map(resp.Table, that.model.prototype.parse);
                                newColl = resp.Table;
                                //that.trigger('buildGrid', resp.Table1,resp.Table);
                                if (!params.refresh) that.trigger('buildGrid', resp.Table1,resp.Table);
                                else that.trigger('refreshColl', resp.Table1,resp.Table);
                            }
                            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;
        },
      

        upsert: function (params) {
            var that = this;
                qp = new Core.Database.QueryParameters();
            var keys = Object.keys(params.coll[0])


            var layout = [];
            var currentHour = 0;
            _.each(params.coll, function(obj){
                currentHour = obj['Hour'];
                _.each(keys,function(key){
                    if (key !== 'Hour') {                        
                       layout.push({Date: new moment(key,'YY/MM/DD').format('YYYY-MM-DD'), MWHLimit:obj[key], Hour: currentHour == 24 ? 0 : currentHour });
                    } 

                });

               
            });
            qp.Add(
                '@LayoutMWHLimitsByDateAndHour',
                'XML',
                app.jsonArrayToXml(
                    layout,
                    [
                        'Date',
                        'Hour',
                        'MWHLimit'
                    ]
                )
            );
            qp.Add("@Start", 'DATE', that.get('start'));
            qp.Add("@submit", 'BIT', params.submit);

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.PWR.UpdatePowerForecast',
                qp,
                {
                    onSuccess: function (resp) {
                        try {

                            if ((resp) && (resp.Table)) {
                               // that.trigger('updated');
                                if (params.submit) app.views.topMessages.showMessage('The Database has been updated and the csv file has been sent by email', { stay: 5000, });
                                else app.views.topMessages.showMessage('The Database has been updated', { stay: 5000, });
                                
                            }
                            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;
        },
    });


    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: 'power-forecast',
        id: 'power-forecast',
        title: 'Power Forecast',
        events: function () {
            return {
                'click #refreshBtn': this.refreshBtn_click,
                'click #clearBtn': this.clearBtn_click,
                'click #submitBtn': this.submitBtn_click,
                'click #saveBtn': this.saveBtn_click,
            };
        },
        bindings: 'data-bind',
        bindingSources: null,
        grids: null,
        itemsColl: null,
        subviews: null,
        viewParams: null,

        initialize: function () {
            this.options.state = app.view_states.loading;
            this.options.onappend = (_.isFunction(this.options.onappend)) ? this.options.onappend : function () { };

            var that = this;

            if (!this.model)
                this.model = new Screen.Models.Main();

            this.grids = {};

            this.itemsColl = new Screen.Collections.Items();
            this.autoFillItemsColl  = new Screen.Collections.AutoFillItems();


            this.bindingSources = {};

            this.subviews = {};

            this.bindEvents();
            
            this.getPermissions();
        },

        
        getPermissions: function () {
            var read = $.inArray('powerforecast_read', app.models.user.get('roles'));
            var write = $.inArray('powerforecast_readWrite', app.models.user.get('roles'));


            var ctx = {
                readonly: (write == -1) ? true : false,
            };
            this.model.set('readOnlyPermission', ctx.readonly);

        },
        bindEvents: function () {
            this.listenTo(this.itemsColl, 'fetch', this.processes_ready);
            this.listenTo(this.model, 'buildGrid',this.buildGrid);
            this.listenTo(this.model, 'refreshColl',this.refreshColl);
            this.listenTo(this.model,'updated',this.updated);
            this.listenTo(this.itemsColl, 'change',this.itemsColl_changed);
            this.listenTo(this.model, 'change:filterGroup',this.filterGroup_changed);
        },
     

        updated: function(){
            var params = this.model.toJSON();
            this.model.fetch({
                start : params.start, 
                refresh: true,
            });
        },

        
        refreshColl: function(columns,allData){
            this.model.set({
                columns: columns,
                allData: allData,
            });
            this.itemsColl.setDataColl(allData,columns);
            this.autoFillItemsColl.setDataColl(columns);
        },

        clearCheckboxes: function(){
            var td = [];
                this.model.set('filterGroup','NONE');
                _.each(document.querySelectorAll("#autofill td"), function(obj,i){
                   td = obj.children[0];
                    if (td){ 
                        td.checked = false;
                    }
                });
        },

        clearBtn_click: function(){
            var that = this;

            var array = [];
            modal = new Modal.Views.Main({
                focusOk: false,
                focusSelector: '#btn-cancel',
                title: app.translate([this, app], "clear_modal_confirm_title"),
                message: app.translate([this, app], "clear_modal_confirm_message"),
                buttons_type: "CONTINUE-CANCEL",
            });
            this.listenToOnce(modal, "continue", function (modal) {
                try {
                    that.itemsColl.clearAllData(that.model.get('columns'));
                    that.clearCheckboxes();

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

        },
        submitBtn_click: function(){              
            var that = this,                
                coll = this.itemsColl.toJSON();
            
            modal = new Modal.Views.Main({
                focusOk: false,
                focusSelector: '#btn-cancel',
                title: app.translate([this, app], "submit_modal_confirm_title"),
                message: app.translate([this, app], "submit_modal_confirm_message"),
                buttons_type: "CONTINUE-CANCEL",
            });
            this.listenToOnce(modal, "continue", function (modal) {
                try {
                        
                        that.model.upsert({coll:coll, submit: true});

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


        },       
        saveBtn_click: function(){              
            var that = this,                
                coll = this.itemsColl.toJSON();
            
            modal = new Modal.Views.Main({
                focusOk: false,
                focusSelector: '#btn-cancel',
                title: app.translate([this, app], "save_modal_confirm_title"),
                message: app.translate([this, app], "save_modal_confirm_message"),
                buttons_type: "CONTINUE-CANCEL",
            });
            this.listenToOnce(modal, "continue", function (modal) {
                try {
                        that.model.upsert({coll:coll, submit: false});

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


        },       
        itemsColl_changed: function(m){      
            var that = this;
            keys = Object.keys(m.changed);

            var columns = [];
            if (that.model.get('arrayDates').length > 0){
                _.each(that.model.get('columns'), function(allColl){
                    if (that.model.get('arrayDates').includes(allColl.Date)) {
                    } else {
                        columns.push(allColl.Date);
                    }
                });
                this.itemsColl.modifyDataColl(that.model.get('arrayDates'),m.get(keys[0]),columns,that.model.get('allData'));
            }else{
                this.model.set({
                    currentDate:  keys[0],
                    currentHour:m.get('Hour'),
                    currentMWHLimit: m.get(keys[0]),
                });
            }
            
            this.model.set({cellChanged: true});
        },

        
        buildGrid: function (columns,allData) {
            var keys = null,
                columnsName = [];
                autoFillColumnsName = [];
            var that = this;
            
            this.itemsColl.setDataColl(allData,columns);
            this.autoFillItemsColl.setDataColl(columns);
           
            this.model.set({
                columns: columns,
                allData: allData,
            });
             // Data grid
            if (columns[0]) {


                keys = Object.keys(columns[0]);

                columnsName.push({
                        "name": 'Hour',
                        "editable": false,
                        "label": app.translate([that, app], 'Hour'),
                        "cell": Backgrid.StringCell.extend({
                            className: function () {
                                return 'string-cell align-center-cell';
                            }
                        }),
                           
                });

                _.each(columns, function (obj) {
                    columnsName.push({
                        "name": obj.Date,
                        "editable": that.model.get('readOnlyPermission') ? false : true,
                        "label": app.translate([that, app], new moment(obj.Date, 'YY/MM/DD').format('MM/DD')),
                        "cell":  Backgrid.NumberCell.extend({
                            className: function () {
                                var model = this.model.toJSON();
                                var column = _.findWhere(columns, {Date: obj.Date});
                                if (column.RowNumber > 0 && column.RowNumber < 8) {
                                    if (model.Hour % 2 == 0) return 'string-cell align-center-cell mwh week1';
                                    else return 'string-cell align-center-cell mwh week1s';
                                }
                                if (column.RowNumber > 7 && column.RowNumber < 15){ 
                                    if (model.Hour % 2 == 0) return 'string-cell align-center-cell mwh week2';
                                    else return 'string-cell align-center-cell mwh week2s';
                                }
                                if (column.RowNumber > 14 && column.RowNumber < 22){   
                                    if (model.Hour % 2 == 0) return 'string-cell align-center-cell mwh week3';
                                    else return 'string-cell align-center-cell mwh week3s';
                                }
                                if (column.RowNumber > 21 && column.RowNumber < 29){   
                                    if (model.Hour % 2 == 0) return 'string-cell align-center-cell mwh week4';
                                    else return 'string-cell align-center-cell mwh week4s';
                                }
                                if (column.RowNumber > 28){   
                                    if (model.Hour % 2 == 0) return 'string-cell align-center-cell mwh week5';
                                    else return 'string-cell align-center-cell mwh week5s';
                                }
                            },
                        }),    
                      
                           
                    });
                });
                that.grid = new Backgrid.Grid({
                    className: 'backgrid table table-hover table-condensed',
                    columns: columnsName,
                    collection: that.itemsColl
                });
                that.$el.find('.processes-grid-container').append(that.grid.render().el);
               
                
                that.model.set({ grid: that.grid });

                 //Auto Fill Grid

                autoFillColumnsName.push({
                    "name": 'Hour',
                    "editable": false,
                    "label": app.translate([that, app],'    '),
                    "cell": Backgrid.StringCell.extend({
                        className: function () {
                            var model = this.model.toJSON();
                            return 'string-cell align-center-cell';
                        }
                    }),
                           
                });

                
                
                _.each(columns, function (obj) {
                    autoFillColumnsName.push({
                        "name": obj.Date,
                        "editable": false,
                        "label": app.translate([that, app], new moment(obj.Date, 'YY/MM/DD').format('MM/DD')),                      
                        "cell": Backgrid.Cell.extend({
                            template: function () {
                                return _.template("<input class='grid-checkbox checkbox' tabindex='-1' type='checkbox'/>");
                            },
                            initialize: function () {
                                Backgrid.Cell.prototype.initialize.apply(this, arguments);
                            },
                            events: {
                                "change .grid-checkbox": "checkboxChanged",
                            },
                            checkboxChanged: function (e) {
                                var column = this.column.toJSON();
                                var isChecked = $(e.target).is(":checked");
                                that.model.set({                                    
                                    dateAutoFill: column.name,
                                    isChecked: isChecked,
                                })
                                that.checkedDate_changed();
                            },
                            render: function () {
                                this.$el.html(this.template());
                                this.delegateEvents();
                                return this;
                            },
                            className: "align-center-cell CheckBoxes date-column",
                        }),
                           
                    });
                });
                var grid = new Backgrid.Grid({
                    className: 'backgrid table table-hover table-condensed',
                    columns: autoFillColumnsName,
                    collection: that.autoFillItemsColl
                });

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


             // Backgrid events
          
            that.grid.collection.on("backgrid:edited", function (model, selected) {
                var date = selected.toJSON().name;
                var m = model.toJSON();
                var MWHLimit =m[date];
                if (that.model.get('cellChanged') === false)                     
                    that.updateGridValues(MWHLimit,date,m.Hour);              
                
                that.model.set({cellChanged: false});
            });

          
         },
        updateGridValues: function(MWHLimit,date,hour){
            var columns = [];
            var that = this;
            if (that.model.get('arrayDates').length > 0){
                _.each(that.model.get('columns'), function(allColl){
                    if (that.model.get('arrayDates').includes(allColl.Date)) {
                    } else {
                        columns.push(allColl.Date);
                    }
                });
                this.itemsColl.modifyDataColl(that.model.get('arrayDates'),MWHLimit,columns,that.model.get('allData'));
            }else{
                this.model.set({
                    currentDate:  date,
                    currentHour:hour,
                    currentMWHLimit: MWHLimit,
                });
            }
            
         },
        //-------------------------------
        //------ Checkboxes Changes -----
        //-------------------------------
        filterGroup_changed: function () {
            var that = this;
            _.each(document.querySelectorAll("#autofill td"), function(obj,i){
               td = obj.children[0];
                if (td){ 
                    if ( that.model.get('filterGroup') === 'NONE') td.checked = false;
                    if ( that.model.get('filterGroup') === 'ALL') td.checked = true;
                    if ( that.model.get('filterGroup') === 'WEEK1' && i > 0 && i < 8) td.checked = true;
                    if ( that.model.get('filterGroup') === 'WEEK2' && i > 7 && i < 15) td.checked = true;
                    if ( that.model.get('filterGroup') === 'WEEK3' && i > 14 && i < 22) td.checked = true;
                    if ( that.model.get('filterGroup') === 'WEEK4' && i > 21 && i < 29) td.checked = true;
                    if ( that.model.get('filterGroup') === 'WEEK5' && i > 28 ) td.checked = true;
                }
            });
            

            var dates = [];
            var array = [];
            
            keys = Object.keys(that.autoFillItemsColl.toJSON()[0]);
            _.each(keys, function(obj,i){
                if (obj !== 'Hour') dates.push(obj);
            });

            if (that.model.get('filterGroup') === 'NONE') {
                array = [];
                this.model.set({arrayDates:array});
            }
            if (that.model.get('filterGroup') === 'ALL') {
                array = dates;
                this.checkedArrayDates_changed(array,true);
            }
            if (that.model.get('filterGroup') === 'WEEK1') {
                _.each(dates, function(obj,i){
                    if (i >= 0 && i < 7) array.push(obj);
                });
                this.checkedArrayDates_changed(array,true);
            }
            if (that.model.get('filterGroup') === 'WEEK2') {
                _.each(dates, function(obj,i){
                    if (i >= 7 && i < 14) array.push(obj);
                });
                this.checkedArrayDates_changed(array,true);
            }
            if (that.model.get('filterGroup') === 'WEEK3') {
                _.each(dates, function(obj,i){
                    if (i >= 14 && i < 21) array.push(obj);
                });
                this.checkedArrayDates_changed(array,true);
            }
            if (that.model.get('filterGroup') === 'WEEK4') {
                _.each(dates, function(obj,i){
                    if (i >= 21 && i < 28) array.push(obj);
                });
                this.checkedArrayDates_changed(array,true);
            }
            if (that.model.get('filterGroup') === 'WEEK5') {
                _.each(dates, function(obj,i){
                    if (i >= 28) array.push(obj);
                });
                this.checkedArrayDates_changed(array,true);

            }
        },
        checkedArrayDates_changed: function (array,isChecked) {
            var arrayDates = null;
            var index = null;
            var dateAutoFill = null;
            var that = this;
            _.each(array,function(obj){
                dateAutoFill = obj;
                arrayDates = that.model.get('arrayDates');
                index = 0;

                
            if (arrayDates.length > 0 && arrayDates.includes(dateAutoFill) && isChecked == false){
                index = arrayDates.indexOf(dateAutoFill);
                arrayDates.splice(index, 1);
                
                that.model.set({arrayDates:arrayDates});
            } else if ((arrayDates.length === 0 || !arrayDates.includes(dateAutoFill)) && isChecked == true) {
                arrayDates.push(dateAutoFill);
                that.model.set({arrayDates:arrayDates});
            }

            });
       

        },   
        checkedDate_changed: function () {
            var dateAutoFill = this.model.get('dateAutoFill')
            var isChecked = this.model.get('isChecked')
            var arrayDates = this.model.get('arrayDates');
            var index = 0;


            if (arrayDates.length > 0 && arrayDates.includes(dateAutoFill) && isChecked == false){
                index = arrayDates.indexOf(dateAutoFill);
                arrayDates.splice(index, 1);
                
                this.model.set({arrayDates:arrayDates});
            } else if ((arrayDates.length === 0 || !arrayDates.includes(dateAutoFill)) && isChecked == true) {
                arrayDates.push(dateAutoFill);
                this.model.set({arrayDates:arrayDates});
            }
            

        },

        render: function (container, viewParams) {
            var that = this;

            this.viewParams = viewParams;

            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) {
                    if (!that.options.i18n) that.options.i18n = {};

                    app.getI18NJed(
                        that,
                        that.template,
                        function (i18nJED) {
                            //storing internationalization data
                            that.options.i18n[that.template] = i18nJED;

                            //loading the view and appeding it to the views's $el.
                            that.$el.html(tmp());

                            that.applyBindings();

                            //start: the view was already loaded an is on a div element, but not appended to the main container
                            //here you can perform anything you want DOM related, by getting the dom element via that.$el.find('#id')
                            //or this.$('#id')

                            that.$el.find('.input-date').datepicker();
                            //appending view to the main container
                            that.append(thatContainer, that.$el);



                            //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('YYYY-MM-DD');     
                           
                            that.model.set(fixedParams);

                            //Call first refresh.
                            var params = that.model.toJSON();

                            
                            that.model.fetch({
                                start : params.start,                                  
                                refresh: false,
                            });

                        },
                        true,
                        customPath
                    );
                },
                customPath
            );
        },

        processes_ready: function (newColl) {
            try {
                var that = this;
                if (newColl) {
                    that.model.set({allData: newColl,arrayDates:[]});
                    that.clearCheckboxes();
                }
                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); }
        },
        refreshBtn_click: function (e) {
            try {
                var params = this.model.toJSON();
                $(".processes-grid-container").html("");
                $(".auto-fill-grid-container").html("");


                this.itemsColl.reset();
                this.autoFillItemsColl.reset();
                this.model.set({
                    isLoading: true,
                    hasData: false,
                })
       
                this.model.fetch({
                    start: params.start,                    
                    refresh: false,
                });



                app.router.navigate(
                    app.router.resolveURL(
                        app.router.currentModule,
                        _.extend(
                            {},
                            params,
                            {
                                start: new moment(params.start, 'YYYY-MM-DD').format('YYYYMMDD'),                        
                            }
                        ),
                        false
                    ),
                    { trigger: false, }
                );
                
                
            }
            catch (Error) { console.error(Error.stack); }
        },

        //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.closeSubviews();
            this.remove();
            this.unbindViewScopedEvents();
            this.unbind();
        },
        closeSubviews: function () {
            _.each(this.subviews, function (sview) {
                sview.close();
            });
        },
        show: function () {
            this.options.state = app.view_states.shown;

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

            this.hideSubviews();

            this.$el.hide();
            this.unbind();
            this.stopListening();
        },
        hideSubviews: function () {
            _.each(this.subviews, function (sview) {
                sview.hide();
            });
        },
        preRender: function () {
            app.models.subnavbar.set("subnavbar", false);
        },
        reRender: function (viewParams) {
            try {
                this.refresh(viewParams);
            } catch (Error) { }
        },
    });

    Screen.Collections.Items = Backbone.Collection.extend({
        currentCollection: [],
        setDataColl: function (data) {
            var collection = [];
            collection = this.setTopAndBottomData(data);
            this.set(collection).trigger('fetch');
        },
        clearAllData: function(columns){
            
            var newColl = [];
            var lastHour = null;
            var collection = [];
            var array = [];
            var tempData = [];
            var data = [];
            
            _.each(columns, function(column){
                for (var i = 0; i <24; i++){
                    array.push({Date :column.Date, Hour: i, MWHLimit: 0})
                }
            });

             // Sorted by Date
            var sortedArrayByDate = array.sort((a, b) => b.Date - a.Date);

            // Sorted by Hour
            for (var i = 0; i < 24; i++) {
                tempData = _.where(sortedArrayByDate, {Hour: i});
               
                _.each(tempData, function(obj){                
                    data.push(obj)
                });
            }

            _.each(data, function(obj,i){
                if (lastHour === null || obj.Hour != lastHour) {
                    lastHour = obj.Hour;
                    if (i > 0){
                        collection.push(newColl);
                        newColl = [];
                    }
                    
                } 
                if (obj.Hour === lastHour){
                    newColl[obj.Date] = obj.MWHLimit;
                    newColl['Hour'] = lastHour;
                }
            });
            
            collection.push(newColl);
            this.set(collection).trigger('fetch');
        },
        modifyDataColl:function(dates,MWHLimit,columns,allData){
            var coll= [];

            _.each(dates,function(obj,i){
                
                for (var i = 0; i<24; i++){
                    coll.push({
                       Date: obj,
                       Hour: i,
                       MWHLimit:MWHLimit
                    });
                }
            });
            
            var newColl = this.mergeCollections(coll,columns,allData);
            if (newColl !== 0) this.set(newColl).trigger('fetch',this.currentCollection);
        },

        mergeCollections(rawData,columns,allData){

            var data = [];
            var tempData = [];            
            var remainData = [];
            var tempRemainData = []; 



            _.each(allData, function(obj){
                if (columns.includes(obj.Date)) remainData.push(obj);
            });
            var temp = [];
            
            for (var i = 0; i < 24; i++) {
                tempData = _.where(rawData, {Hour: i});
                tempRemainData =  _.where(remainData, {Hour: i});
               
                _.each(tempData, function(obj){                
                    temp.push(obj)
                });
                _.each(tempRemainData, function(obj){                
                    temp.push(obj)
                });

               

                _.each(tempData, function(obj){                
                    data.push(obj)
                });
            }

            data = temp;

            this.currentCollection = data;
            collection = this.setTopAndBottomData(data);
            return collection;
        },
        setTopAndBottomData: function(data){
            var newColl = [];
            var lastHour = null;
            var collection = [];
           
            var topData = [],
                bottomData = [];
            _.each(data,function(obj){
                if (obj.Hour !== 0) topData.push(obj);
                else bottomData.push(obj);
            });

            _.each(topData, function(obj,i){
                if (lastHour === null || obj.Hour != lastHour) {
                    lastHour = obj.Hour;
                    if (i > 0){
                        collection.push(newColl);
                        newColl = [];
                    }
                    
                } 
                if (obj.Hour === lastHour){
                    newColl[obj.Date] = obj.MWHLimit;
                    newColl['Hour'] = lastHour;
                }
            });
            
            collection.push(newColl);

            newColl = [];
            _.each(bottomData, function(obj,i){
                newColl[obj.Date] = obj.MWHLimit;
                newColl['Hour'] = 24;
            });

            
            collection.push(newColl);
            return collection;
            
        },
    });


     Screen.Collections.AutoFillItems = Backbone.Collection.extend({
        setDataColl: function (columns) {
            var newColl = [];
            var collection = [];

            _.each(columns, function(obj,i){
                newColl[obj.Date] = i;
                newColl['Hour'] = '  Auto Fill  ';
            });
            
            collection.push(newColl);
            this.set(collection).trigger('fetch');
        },
    });

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