//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/base/base',
  'modules/slag-chemistry-sample',


    'js/backgrid-0.3.5/extensions/valid-min-max-cell/backgrid-valid-min-max-cell',
  'backgrid/infinator',
  'backgrid/calendar-cell',
  'backgrid/moment-cell',

  'js/jquery.timepicker/jquery.timepicker',
  'backgrid/time-cell'
],
    function (app, T, Backgrid, moment, Base, SlagChemistrySamples ) {

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


    Screen.Models.ItemSlag = Backbone.Epoxy.Model.extend({
        parse: function (obj) {
            var result = {
                heatName: obj.HeatName,
                typeName: obj.TypeName,
                timestamp: new moment(obj.Timestamp).format("YYYY-MM-DD HH:mm:ss"),
                MgO:                     obj.MgO,
                CaO:                     obj.CaO,
                Fe2O3:                   obj.Fe2O3,
                Al2O3:                   obj.Al2O3,
                SiO2:                    obj.SiO2,
                MnO:                     obj.MnO,
                Cr2O3:                   obj.Cr2O3,
                TiO2:                    obj.TiO2,
                P2O5:                    obj.P2O5,
                SO3:                     obj.SO3,
                B3ratio:                 obj.B3ratio,
                FeO:                     obj.FeO,
                HiCal:                   obj.HiCal,
                total:                   obj.Total,
                refractoryWear:          obj.RefractoryWear,
                steelLoss:               obj.FeinSlag,

                b3Max:                   obj.B3Max,
                b3Min:                   obj.B3Min,
                feOMax:                  obj.FeOMax,
                feOMin:                  obj.FeOMin,
                mgOMax:                  obj.MgOMax,
                mgOMin:                  obj.MgOMin,
                refractoryWearThreshold: obj.RefWearLimit,
            };





            return result;
        },
    });

    Screen.Collections.Items = Backbone.Collection.extend({
        model: Screen.Models.ItemSlag,

        isFetching: false,
        currentPage: 1,
        pageSize: 50,

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

            if (options.refresh) {
                this.resetPagination(true);
                this.fixedParameters = [
                    { Name: '@from', Type: 'DATE', Value: params.from, },
                    { Name: '@to', Type: 'DATE', Value: params.to, },
                    { Name: '@code', Type: 'CHAR', Value: params.code, },
                    { Name: '@timeZoneCode', Type: 'CHAR(10)', Value: params.timezoneCode },
                ];


            }

            this.isFetching = true;

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

            if (!options.refresh) {
                qp.Add('@fromRow', 'INT', (this.currentPage - 1) * this.pageSize);
                qp.Add('@rowsToFetch', 'INT', this.pageSize);
            } 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 + '.LAB.LMFGetSlagChemistrySamplesReport',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if (resp) {

                                console.log("re8", resp);
                                if (resp.Table) {
                                    var newColl = _.map(resp.Table, that.model.prototype.parse);

                                    var method = (options.refresh) ? 'set' : 'add';

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

                                    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 {
                                    console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                    app.views.topMessages.showMessage('SERVER RESPONSE NOT VALID', { stay: 5000, });
                                }
                            }
                        }
                        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);
            }
        },

    });
    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {

            from: new moment().format('YYYY-MM-DD'),
            to: new moment().add(1, 'days').format('YYYY-MM-DD'),

            typeCode: null,
            typeName: null,
            types: [],

            hasData: false,
            isLoading: false,
        },
        computeds: {
            from$: {
                deps: ['from'],
                get: function (value) {
                    return value;
                },
                set: function (value) {
                    return { from: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                },
            },
            to$: {
                deps: ['to'],
                get: function (value) {
                    return value;
                },
                set: function (value) {
                    return { to: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                },
            },
        },

        fetchTypes: function () {
            var that = this,
                qp = new Core.Database.QueryParameters();

            //qp.Add('@onlyEnabled', 'BIT', 1);

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + ".CAT.LMFGetSlagChemistrySampleTypes",
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var records = resp.Table;

                                var newItems = _.map(records, function (obj) {
                                    return { value: obj.Code, label: obj.Name, };
                                });

                                that.set("types", newItems);
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error("Server response not valid.");
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );

            return this;
        },
    });

    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: 'slag-chemistry-samples-report-lmf',
        id: 'slag-chemistry-samples-report-lmf',
        title: 'LMF Slag Chimestries Report',
        events: function () {
            return {
                'click #refreshBtn': this.refreshBtn_click,
                "click .btn-export-to-excel": this.exportToExcel,
            };
        },
        bindings: 'data-bind',
        bindingSources: null,
        items: null,
        eafProcess: 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.model.fetchTypes();
            this.items = new Screen.Collections.Items();

            this.bindingSources = {
                eafProcess: this.eafProcess,
            };

            this.grids = { items: null };

            this.subviews = {
            };


            this.autoRefresh = {
                enabled: null
                , toid: null
                , every: 5 * 1000
            };

            this.bindEvents();
        },
        bindEvents: function () {
            //this function should be in every view that uses listenTo anywhere
            //all the model bindings or view-model binding should be here, to manage
            //the show/hide view easily
            this.listenTo(this.model, "change:typeCode", this.model_change_typeCode);
            this.listenTo(this.items, 'fetch', this.items_ready)
        },

        items_ready: function () {
            try {
                var that = this;
                setTimeout(
                    function () {
                        that.model.set({
                            hasData: (that.items.length > 0),
                            isLoading: false,
                        });
                    },
                    100
                );

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


        _refresh: function (opt) {
            //console.log('autorefresh: ' + new Date().toString()); 
            if (this.autoRefresh.toid !== null) {
                clearTimeout(this.autoRefresh.toid);
                this.autoRefresh.toid = null;
            }

            this.refreshHeat(opt);

            if (this.autoRefresh.enabled == true) {
                var that = this 

                this.autoRefresh.toid = setTimeout(
                    function () { that._refresh(); },
                    this.autoRefresh.every
                );
            }
        },
        refresh: function (viewParams) {
            var fixedParams = _.extend({}, viewParams);
            if (viewParams.from)
                fixedParams.from = new moment(fixedParams.from, 'YYYYMMDD').format('YYYY-MM-DD');
            if (viewParams.to)
                fixedParams.to = new moment(fixedParams.to, 'YYYYMMDD').format('YYYY-MM-DD');
            if (viewParams.typeCode)
                fixedParams.typeCode = (viewParams.typeCode == '-') ? null : viewParams.typeCode;
        
            this.model.set(fixedParams);

            this._refresh({
                reset: true,
                params: _.extend(
                    {},
                    fixedParams,
                    {}
                ),
            });
        },
        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();

                            var grid = that.grids = new Backgrid.Grid({
                                className: 'backgrid table table-hover',
                                columns: [].concat(
                                    {
                                        name: 'heatName',
                                        label: app.translate(that, 'heat_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.StringCell.extend({
                                            orderSeparator: '',
                                            className: 'string-cell align-center-cell heatName',
                                        }),
                                    },
                                    {
                                        name: 'typeName',
                                        label: app.translate(that, 'typeName_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.StringCell.extend({
                                            orderSeparator: '',
                                            className: 'string-cell align-center-cell typeName',
                                        }),
                                    },
                                    [
                                    {
                                        name: 'timestamp',
                                        editable: false,
                                        sortable:false,
                                        label: app.translate(that, 'timestamp_col'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-right-cell timestamp-cell date-cell timestamp-date',
                                            formatter: Backgrid.Extension.DatetimeToDateFormatter.extend({
                                                columnName: 'timestamp',
                                                displayFormat: app.translate([that, app], 'MM/DD/YYYY'),
                                                modelDateFormat: 'YYYY-MM-DD',
                                            }),
                                            editor: Backgrid.Extension.CalendarCellEditor.extend({
                                                dateFormat: 'mm/dd/yy',
                                                momentFormat: app.translate([that, app], 'mmddyyyy'),
                                            }),
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            attributes: {
                                                colspan: 2,
                                            },
                                            className: 'timestamp-date'
                                        }),
                                    },
                                    {
                                        name: 'timestamp',
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-left-cell timestamp-cell time-cell timestamp-time',
                                            formatter: Backgrid.Extension.DatetimeToTimeFormatter.extend({
                                                columnName: ' timestamp',
                                                displayFormat: app.translate([that, app], 'HH:mm'),
                                                modelDateFormat: 'YYYY-MM-DD',
                                            }),
                                            editor: Backgrid.Extension.TimeCellEditor.extend({
                                                showOn: false,
                                            }),
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            attributes: {
                                                style: 'display: none;',
                                            },
                                            className: 'timestamp-time'
                                        }),
                                    }],
                                    {
                                        name: 'MgO',
                                        label: app.translate(that, 'mgO_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.NumberCell).extend({
                                            className: 'number-cell align-right-cell element',
                                            minProp: 'mgOMin',
                                            maxProp: 'mgOMax',
                                            invalidMinMessage: function (value, limit, includeLimit) {
                                                return app.translate([that, app], 'value_min_reached_legend', [limit.toFixed(0)]);
                                            },
                                            invalidMaxMessage: function (value, limit, includeLimit) {
                                                return app.translate([that, app], 'value_max_reached_legend', [limit.toFixed(0)]);
                                            },
                                            decimals: 1,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),
                                    },
                                    {
                                        name: 'CaO',
                                        label: app.translate(that, 'caO_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell element',
                                            decimals: 1,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),
                                    },
                                    {
                                        name: 'Fe2O3',
                                        label: app.translate(that, 'fe2O3_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.NumberCell).extend({
                                            className: 'number-cell align-right-cell element',
                                            minProp: 'feOMin',
                                            maxProp: 'feOMax',
                                            invalidMinMessage: function (value, limit, includeLimit) {
                                                return app.translate([that, app], 'value_min_reached_legend', [limit.toFixed(0)]);
                                            },
                                            invalidMaxMessage: function (value, limit, includeLimit) {
                                                return app.translate([that, app], 'value_max_reached_legend', [limit.toFixed(0)]);
                                            },
                                            decimals: 1,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),
                                    },
                                    {
                                        name: 'Al2O3',
                                        label: app.translate(that, 'al2O3_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell element',
                                            decimals: 1,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),
                                    },
                                    {
                                        name: 'SiO2',
                                        label: app.translate(that, 'siO2_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell element',
                                            decimals: 1,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),
                                    },
                                    {
                                        name: 'MnO',
                                        label: app.translate(that, 'mnO_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell element',
                                            decimals: 1,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),
                                    },
                                    {
                                        name: 'P2O5',
                                        label: app.translate(that, 'p2O5_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell element',
                                            decimals: 1,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),
                                    },
                                    {
                                        name: 'B3ratio',
                                        label: app.translate(that, 'b3Ratio_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.Extension.MakeCellValidMinMax(Backgrid.NumberCell).extend({
                                            className: 'number-cell align-right-cell element',
                                            minProp: 'b3Min',
                                            maxProp: 'b3Max',
                                            invalidMinMessage: function (value, limit, includeLimit) {
                                                return app.translate([that, app], 'value_min_reached_legend', [limit]);
                                            },
                                            invalidMaxMessage: function (value, limit, includeLimit) {
                                                return app.translate([that, app], 'value_max_reached_legend', [limit]);
                                            },
                                            decimals: 1,

                                        }),
                                        
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),
                                    },
                                    {
                                        name: 'FeO',
                                        label: app.translate(that, 'feO_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell element',
                                            decimals: 1,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),
                                    },
                                    {
                                        name: 'HiCal',
                                        label: app.translate(that, 'HiCal_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell element',
                                            decimals: 1,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),
                                    },
                                    {
                                        name: 'total',
                                        label: app.translate(that, 'total_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell element',
                                            decimals: 1,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),
                                    },
                                    {
                                        name: 'refractoryWear',
                                        label: app.translate(that, 'refractoryWear_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: function () {
                                                if (parseFloat(this.model.get('refractoryWear')) >= parseFloat(this.model.get('refractoryWearThreshold')))
                                                    return 'number-cell element refWearGreen';
                                                if (parseFloat(this.model.get('refractoryWear')) < parseFloat(this.model.get('refractoryWearThreshold')))
                                                    return 'number-cell element refWearRed';
                                                else return 'number-cell element';
                                            },
                                            decimals: 1,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),
                                    },
                                    {
                                        name: 'steelLoss',
                                        label: app.translate(that, 'steelLoss_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell element',
                                            decimals: 1,
                                        }),
                                        headerCell: Backgrid.HeaderCell.extend({
                                            className: 'element',
                                        }),
                                    },
                                ),
                                collection: that.items,
                                footer: Backgrid.Extension.Infinator.extend({
                                    scrollToTop: false,
                                }),
                            });

                            

                            
                            that.$el.find('.items-grid-container').append(grid.render().el);
                            //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.from)
                                fixedParams.from = new moment(fixedParams.from, 'YYYYMMDD').format('YYYY-MM-DD');
                            if (fixedParams.to)
                                fixedParams.to = new moment(fixedParams.to, 'YYYYMMDD').format('YYYY-MM-DD');
                            if (fixedParams.typeCode)
                                fixedParams.typeCode = (fixedParams.typeCode == '-') ? null : fixedParams.typeCode;

                            that.model.set(fixedParams); 


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

                            that._refresh({
                                reset: true,
                                params: _.extend(
                                    {},
                                    params,
                                    {
                                    }
                                ),
                            });

                            //that.startAutoRefresh();
                        },
                        true,
                        customPath
                    );
                },
                customPath
            );
        },
        model_change_equipmentTypeId: function (model, value, opt) {
            try {
                if (!opt)
                    opt = {};

                if (opt.from != 'render') {
                    this.model.set({ typeName: null });
                }

            } catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        refreshHeat: function (options) {
            var that = this,
                attrs = this.model.toJSON(),
                opt = _.extend({}, { params: {  }, }, options);

            if ((attrs.mainView == true) && ((opt.refresh == true) || (opt.reset == true)))
                this.model.set('isLoadingProcess', true);


            this.model.set({
                isLoading: true,
                hasData: false,
            })

            this.items.fetch({
                from: attrs.from,
                to: attrs.to,
                code: (attrs.typeCode == null || attrs.typeCode == '') ? null : attrs.typeCode,
                timezoneCode: app.models.user.get('timezoneCode'),
                refresh: true,
            });

        },
        refreshBtn_click: function (e) {
            try {
                var params = this.model.toJSON();

                app.router.navigate(
                    app.router.resolveURL(
                        app.router.currentModule,
                        _.extend(
                            {},
                            params,
                            {
                                from: new moment(params.from, 'YYYY-MM-DD').format('YYYYMMDD'),
                                to: new moment(params.to, 'YYYY-MM-DD').format('YYYYMMDD'),
                                typeCode: (params.typeCode == null || params.typeCode == '') ? '-' : params.typeCode,
                            }
                        ),
                        false
                    ),
                    { trigger: false, }
                );

                this._refresh({
                    reset: true,
                    params: _.extend(
                        {},
                        params,
                        {}
                    ),
                });

                window.scrollTo(0, 0);
            }
            catch (Error) { console.error(Error.stack); }
        },

        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.stopAutoRefresh();

            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) { }
        },
        startAutoRefresh: function () {
            try {
                if (this.autoRefresh.enabled !== true) {
                    var that = this;

                    if (this.autoRefresh.toid != null) {
                        clearTimeout(this.autoRefresh.toid);
                        this.autoRefresh.toid = null;
                    }

                    this.autoRefresh.enabled = true;

                    //use a timeout to execute the first refresh to return the handle to the start function caller.
                    //So when the caller finish it will do the first refresh.
                    this.autoRefresh.toid = setTimeout(
                        function () { that._refresh(); },
                        1
                    );
                }
            } catch (Error) { console.error(Error.stack); }
        },
        stopAutoRefresh: function () {
            if (this.autoRefresh.toid != null) {
                clearTimeout(this.autoRefresh.toid);
                this.autoRefresh.toid = null;
            }
            this.autoRefresh.enabled = false;
        },
        exportToExcel: function () {
            var that = this,
                from = that.model.get('from'),
                to = that.model.get('to'),
                code = (that.model.get('typeCode') == "") ? null : that.model.get('typeCode'),
                timezoneCode = app.models.user.get('timezoneCode')

            var params = [
                { Name: '@fromRow', Type: 'INT', Value: -1 },
                { Name: '@toRow', Type: 'INT', Value: -1 },
                { Name: '@from', Type: 'DATETIME', Value: from, },
                { Name: '@to', Type: 'DATETIME', Value: to, },
                { Name: '@code', Type: 'VARCHAR', Value: code },
                { Name: '@timeZoneCode', Type: 'VARCHAR', Value: timezoneCode }
       
            ];

            var QP = new QueryParameters();

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


            var data = {
                Data: [],
                ConnectionStringName: 'APP',
                FileName: 'Slag Report',
                TemplateFileFullPath: 'generic.xls',
                SQLDataSources: [
                    {
                        Name: 'data',
                        DatabaseParameters: {
                            DBEngine: 'SQLSERVER',
                            Procedure: app.DatabaseNames.MES + '.LAB.LMFGetSlagChemistrySamplesReport',
                            QueryParameters: QP,
                        },
                    },
                ]
            },
                chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
                chari = 0;
            data.Data.push({
                SheetName: 'Data',
                RowsData: [{
                    CellsData:
                        [
                            { Column: chars[chari++], Value: 'Heat' },
                            { Column: chars[chari++], Value: 'Time' },
                            { Column: chars[chari++], Value: 'Type' },
                            { Column: chars[chari++], Value: 'MgO' },
                            { Column: chars[chari++], Value: 'CaO' },
                            { Column: chars[chari++], Value: 'Fe2O3' },
                            { Column: chars[chari++], Value: 'Al2O3' },
                            { Column: chars[chari++], Value: 'SiO2' },
                            { Column: chars[chari++], Value: 'MnO' },
                            { Column: chars[chari++], Value: 'Cr2O3' },
                            { Column: chars[chari++], Value: 'TiO2' },
                            { Column: chars[chari++], Value: 'P2O5' },
                            { Column: chars[chari++], Value: 'SO3' },
                            { Column: chars[chari++], Value: 'B3ratio' },
                            { Column: chars[chari++], Value: 'FeO' },
                            { Column: chars[chari++], Value: 'HiCal' },
                            { Column: chars[chari++], Value: 'Dolo' },
                            { Column: chars[chari++], Value: 'ProSlag' },
                            { Column: chars[chari++], Value: 'TotalSlagVolume' },
                            { Column: chars[chari++], Value: 'LbsMgOAdded' },
                            { Column: chars[chari++], Value: 'LbsMgOnSlag' },
                            { Column: chars[chari++], Value: 'FeinSlag' },
                            { Column: chars[chari++], Value: 'RefractoryWear' },
                            { Column: chars[chari++], Value: 'Total' },
                            { Column: chars[chari++], Value: 'Comments' },
                        ],
                }],
                StartRowIndex: 1,
            });
            chari = 0;
            data.Data.push({
                SheetName: 'Data',
                RowsData: [],
                StartRowIndex: 2,
                DataSourceName: 'data',
                DataSourceTableIndex: 0,
                SQLCellsData:
                    [
                        { ExcelColumnName: chars[chari++], SQLDataColumnName: 'HeatName', DataType: 'String' },
                        { ExcelColumnName: chars[chari++], SQLDataColumnName: 'TimestampString', DataType: 'String' },
                        { ExcelColumnName: chars[chari++], SQLDataColumnName: 'TypeName', DataType: 'String' },
                        { ExcelColumnName: chars[chari++], SQLDataColumnName: 'MgO', DataType: 'Float' },
                        { ExcelColumnName: chars[chari++], SQLDataColumnName: 'CaO', DataType: 'Float' },
                        { ExcelColumnName: chars[chari++], SQLDataColumnName: 'Fe2O3', DataType: 'Float' },
                        { ExcelColumnName: chars[chari++], SQLDataColumnName: 'Al2O3', DataType: 'Float' },
                        { ExcelColumnName: chars[chari++], SQLDataColumnName: 'SiO2', DataType: 'Float' },
                        { ExcelColumnName: chars[chari++], SQLDataColumnName: 'MnO', DataType: 'Float' },
                        { ExcelColumnName: chars[chari++], SQLDataColumnName: 'Cr2O3', DataType: 'Float' },
                        { ExcelColumnName: chars[chari++], SQLDataColumnName: 'TiO2', DataType: 'Float' },
                        { ExcelColumnName: chars[chari++], SQLDataColumnName: 'P2O5', DataType: 'Float' },
                        { ExcelColumnName: chars[chari++], SQLDataColumnName: 'SO3', DataType: 'Float' },
                        { ExcelColumnName: chars[chari++], SQLDataColumnName: 'B3ratio', DataType: 'Float' },
                        { ExcelColumnName: chars[chari++], SQLDataColumnName: 'FeO', DataType: 'Float' },
                        { ExcelColumnName: chars[chari++], SQLDataColumnName: 'HiCal', DataType: 'Float' },
                        { ExcelColumnName: chars[chari++], SQLDataColumnName: 'Dolo', DataType: 'Float' },
                        { ExcelColumnName: chars[chari++], SQLDataColumnName: 'ProSlag', DataType: 'Float' },
                        { ExcelColumnName: chars[chari++], SQLDataColumnName: 'TotalSlagVolume', DataType: 'Float' },
                        { ExcelColumnName: chars[chari++], SQLDataColumnName: 'LbsMgOAdded', DataType: 'Float' },
                        { ExcelColumnName: chars[chari++], SQLDataColumnName: 'LbsMgOnSlag', DataType: 'Float' },
                        { ExcelColumnName: chars[chari++], SQLDataColumnName: 'FeinSlag', DataType: 'Float' },
                        { ExcelColumnName: chars[chari++], SQLDataColumnName: 'RefractoryWear', DataType: 'Float' },
                        { ExcelColumnName: chars[chari++], SQLDataColumnName: 'Total', DataType: 'Float' },
                        { ExcelColumnName: chars[chari++], 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.refreshProcesses();
                    that.model.setExportButtonExporting(false);
                    console.error(resp);
                }
            );
        },
    });



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