//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',
    'js/d3v4/d3.v4',

    'js/jquery.clearsearch/jquery.clearsearch',
    'js/backgrid-0.3.5/extensions/valid-min-max-cell/backgrid-valid-min-max-cell',

    'backgrid/calendar-cell',
    'backgrid/moment-cell',

    'js/jquery.timepicker/jquery.timepicker',
    'backgrid/time-cell'

],
    function (app, T, Backgrid, moment, Modal, d3) {
        //replace all 'Screen' with your view's name.
        var Screen = {
            Models: {},
            Views: {},
            Collections: {},
        };

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


                hasData_silos: false,
                isLoading_silos: true,

                hasData_south: false,
                isLoading_south: true,

                hasData_north: false,
                isLoading_north: true,

                hasData_inj: false,
                isLoading_inj: true,

                start: new moment().subtract(1, 'days').format('MM/DD/YYYY'),
                end: new moment().format('MM/DD/YYYY'),

            },
            initialize: function () {
                this.itemsSilos = new Screen.Collections.ItemsSilos();
                this.itemsSouth = new Screen.Collections.ItemsSouth();
                this.itemsNorth = new Screen.Collections.ItemsNorth();
                this.itemsInj = new Screen.Collections.ItemsInj();
            },
            computeds: {
                endDatetime: {
                    deps: ['end'],
                    get: function (end) {
                        var todayDate = new moment().format('MM/DD/YYYY');
                        if (end === todayDate) {
                            return new moment().format('YYYY-MM-DD HH:mm:ss');
                        } else {
                            return new moment(end, 'MM/DD/YYYY').format('YYYY-MM-DD') + ' 00:00:00'
                        }
                    },
                },
                startDatetime: {
                    deps: ['start'],
                    get: function (start) {
                        return new moment(start, 'MM/DD/YYYY').format('YYYY-MM-DD') + ' 00:00:00'
                    },
                },
                lastUpdateDatetime: {
                    deps: ['end'],
                    get: function (end) {
                        var todayDate = new moment().format('MM/DD/YYYY');
                        if (end === todayDate) {
                            return new moment().format('MM/DD/YYYY HH:mm:ss');
                        } else {
                            return new moment(end, 'MM/DD/YYYY').format('MM/DD/YYYY') + ' 00:00:00'
                        }
                    },
                },
                hasData: {
                    deps: ['hasData_silos', 'hasData_south', 'hasData_north', 'hasData_inj'],
                    get: function (silos, south, north, inj) {
                        return (silos || south || north || inj);
                    },
                },
                isLoading: {
                    deps: ['isLoading_silos', 'isLoading_south', 'isLoading_north', 'isLoading_inj'],
                    get: function (silos, south, north, inj) {
                        if (!silos && !south && !north && !inj) return false;
                        else return true;
                    },
                },
            },

            fetchData: function () {
                var that = this,
                    qp = new Core.Database.QueryParameters();
                this.fixedParameters = [
                    { Name: '@timeZoneCode', Type: 'CHAR(10)', Value: app.models.user.get('timezoneCode') },
                    { Name: '@start', Type: 'DATETIME', Value: this.get('startDatetime') },
                    { Name: '@end', Type: 'DATETIME', Value: this.get('endDatetime') },
                ];
                _.each(this.fixedParameters, function (qpParams) {
                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });


                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.MES.GetSilosReport',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if (resp) {
                                    if (resp.Table) that.itemsSilos.setDataColl(resp.Table);
                                    if (resp.Table1) that.itemsSouth.setDataColl(resp.Table1);
                                    if (resp.Table2) that.itemsNorth.setDataColl(resp.Table2);
                                    if (resp.Table3) that.itemsInj.setDataColl(resp.Table3);
                                }
                                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: true,
                    },
                    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 'silos-report';
            } catch (Error) { }
        }

        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'silos-report'
            , id: 'silos-report'
            , title: 'Silos Report'

            //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 {
                    'click #refreshBtn': this.refreshBtn_click,
                    'click #printBtn': this.printBtn_click,
                    'click #forwardNavBtn': this.forwardNavBtn_click,
                    'click #backNavBtn': this.backNavBtn_click,
                    "click .btn-export-to-excel": this.exportToExcel,
                };
            }
            , bindings: 'data-bind'

            , viewParams: null

            , baghouseChart: null
            , baghouseChartPrint: 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.bindEvents();
            }


            , forwardNavBtn_click: function () {
                this.UpdateNav(true);
            }
            , backNavBtn_click: function () {
                this.UpdateNav(false);
            }

            , printBtn_click: function () {
                window.print();
                return false;
            }

            , refreshBtn_click: function (model) {
                this.UpdateURL();
                this.refresh();
            }


            , bindEvents: function () {
                this.listenTo(this.model.itemsSilos, 'fetch', this.itemsSilos_ready);


                this.listenTo(this.model.itemsSouth, 'fetch', this.itemsSouth_ready);
                this.listenTo(this.model.itemsNorth, 'fetch', this.itemsNorth_ready);
                this.listenTo(this.model.itemsInj, 'fetch', this.itemsInj_ready);
            }

            , 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.$el.find('.input-date').datepicker();


                                var grid_south = new Backgrid.Grid({
                                    className: 'grid-styles table',
                                    columns: [
                                        {
                                            name: 'Silo',
                                            label: 'Silo',
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'TotalCapacity',
                                            label: 'Total Capacity',
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'PercentageFull',
                                            label: '% Full',
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'TrucksToFill',
                                            label: 'Trucks To Fill',
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell element shift-crew-column',
                                            }),
                                        },
                                    ],
                                    collection: that.model.itemsSouth,
                                    header: Backgrid.Header.extend({
                                        initialize: function (options) {
                                            Backgrid.Header.prototype.initialize.apply(this, arguments);
                                            this.listenTo(this.collection, 'backgrid:sort', this.collection_backgrid_sort);
                                        },
                                    }),
                                });

                                that.$el.find('.items-grid-container-south').append(grid_south.render().el);


                                var grid_north = new Backgrid.Grid({
                                    className: 'grid-styles table',
                                    columns: [
                                        {
                                            name: 'Silo',
                                            label: 'Silo',
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'TotalCapacity',
                                            label: 'Total Capacity',
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'PercentageFull',
                                            label: '% Full',
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'TrucksToFill',
                                            label: 'Trucks To Fill',
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell element shift-crew-column',
                                            }),
                                        },
                                    ],
                                    collection: that.model.itemsNorth,
                                    header: Backgrid.Header.extend({
                                        initialize: function (options) {
                                            Backgrid.Header.prototype.initialize.apply(this, arguments);
                                            this.listenTo(this.collection, 'backgrid:sort', this.collection_backgrid_sort);
                                        },
                                    }),
                                });

                                that.$el.find('.items-grid-container-north').append(grid_north.render().el);

                                var grid_inj = new Backgrid.Grid({
                                    className: 'grid-styles table',
                                    columns: [
                                        {
                                            name: 'Silo',
                                            label: 'Silo',
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'TotalCapacity',
                                            label: 'Total Capacity',
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'PercentageFull',
                                            label: '% Full',
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'TrucksToFill',
                                            label: 'Trucks To Fill',
                                            editable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell element shift-crew-column',
                                            }),
                                        },
                                    ],
                                    collection: that.model.itemsInj,
                                    header: Backgrid.Header.extend({
                                        initialize: function (options) {
                                            Backgrid.Header.prototype.initialize.apply(this, arguments);
                                            this.listenTo(this.collection, 'backgrid:sort', this.collection_backgrid_sort);
                                        },
                                    }),
                                });

                                that.$el.find('.items-grid-container-inj').append(grid_inj.render().el);

                                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
                );
            }
            , recalculateComputedEndValues: function () {
                // This function save the current End picker Value, then it changes to a different End value and the last step is return to the current value
                // This allows to call the "Computed" function that detects the End changes
                var params = this.model.toJSON();
                var currentEnd = params.end;
                this.model.set({
                    end: new moment(params.end, 'MM/DD/YYYY').subtract(1, 'days').format('MM/DD/YYYY'),
                });

                this.model.set({
                    end: new moment(currentEnd, 'MM/DD/YYYY').format('MM/DD/YYYY'),
                });
            }

            , refresh: function () {
                try {
                    this.recalculateComputedEndValues();

                    var params = this.model.toJSON();

                    if (params.start >= params.end) {
                        this.model.set({
                            start: new moment(params.end, 'MM/DD/YYYY').subtract(1, 'days').format('MM/DD/YYYY')
                        });
                    }

                    this.$el.find('.southSilos').html('');
                    this.$el.find('.northSilos').html('');
                    this.$el.find('.injectionLime').html('');

                    this.model.set({
                        isLoading_silos: true,
                        hasData_silos: false,
                    });

                    // reload collections 
                    this.model.fetchData();


                }
                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); }
            }

            , itemsSouth_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_south: (that.model.itemsSouth.length > 0),
                                isLoading_south: false,
                            });
                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            }
            , itemsNorth_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_north: (that.model.itemsNorth.length > 0),
                                isLoading_north: false,
                            });
                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            }
            , itemsInj_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_inj: (that.model.itemsInj.length > 0),
                                isLoading_inj: false,
                            });

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


            , itemsSilos_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_silos: (that.model.itemsSilos.length > 0),
                                isLoading_silos: false,
                            });
                            that.silos_chart(".southSilos", 1800, 'SOUTH');
                            that.silos_chart(".southSilos_print", 1150, 'SOUTH');

                            that.silos_chart(".northSilos", 1800, 'NORTH');
                            that.silos_chart(".northSilos_print", 1150, 'NORTH');


                            that.silos_chart(".injectionLime", 1800, 'INJ');
                            that.silos_chart(".injectionLime_print", 1150, 'INJ');

                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            }
            //Silos charts
            , silos_chart: function (id, width, type) {
                var silosData = this.model.itemsSilos.toJSON();
                var minDatetime = this.model.get('startDatetime');
                var maxDatetime = this.model.get('endDatetime');


                var chartWidth = width;
                var chartHeight = 410;
                var chartMarginLeft = 80;
                var maxAxisBottom = chartWidth - 100;
                var maxAxisLeftHeight = 300;
                if (silosData.length > 0) {
                    minValueBottomAxis = maxAxisBottom / (2 * silosData.length);
                    var svg = d3.select(id)
                        .append("svg")
                        .attr("width", chartWidth + chartMarginLeft)
                        .attr("height", chartHeight)
                        .append("g")
                        .attr("transform",
                            "translate(" + chartMarginLeft + "," + 350 + ")");
                    var x = d3.scaleTime()
                        .domain([new Date(minDatetime), new Date(maxDatetime)])
                        .range([0, maxAxisBottom]);

                    svg.append("g")
                        .attr("class", 'x_text dashed')
                        .call(d3.axisBottom(x).tickSize(-maxAxisLeftHeight).ticks(20))
                        .select(".domain").attr("class", 'wdashed');

                    svg.selectAll("g")
                        .select(".x_text .tick text")
                        .attr("y", function (d, i) {
                            if (i % 2 == 0) return 3
                            else return 17;
                        })
                        .attr("text", function (d, i) {
                            return minDatetime
                        })


                    var y0 = d3.scaleLinear()
                        .domain([0, 100])
                        .range([0, -maxAxisLeftHeight]);

                    svg.append("g")
                        .attr("class", "y0_text dashed")
                        .style("fill", "black")
                        .call(d3.axisLeft(y0))
                        .select(".domain").remove();

                    svg.selectAll("g")
                        .select(".y0_text .tick text")
                        .style("fill", "black")
                        .attr("x", function (d, i) {
                            return -32;
                        });

                    this.model.set({ hasData_silos: true });

                    var chart1 = null;
                    var chart2 = null;
                    var chart3 = null;
                    var chart4 = null;
                    if (type === 'SOUTH') {
                        chart1 = _.where(silosData, { tagName: 'SCC' });
                        chart2 = _.where(silosData, { tagName: 'SHC' });
                        chart3 = _.where(silosData, { tagName: 'SD1' });
                        chart4 = _.where(silosData, { tagName: 'SD2' });
                    }
                    else if (type === 'NORTH') {
                        chart1 = _.where(silosData, { tagName: 'NCC' });
                        chart2 = _.where(silosData, { tagName: 'NHC' });
                        chart3 = _.where(silosData, { tagName: 'ND1' });
                        chart4 = _.where(silosData, { tagName: 'ND2' });
                    } else if (type === 'INJ') {
                        chart1 = _.where(silosData, { tagName: 'ND ' });
                        chart2 = _.where(silosData, { tagName: 'SC ' });
                        chart3 = _.where(silosData, { tagName: 'LL ' });

                    }
                    svg.append("path")
                        .datum(chart1)
                        .attr("fill", "none")
                        .attr("stroke", "blue")
                        .attr("stroke-width", 1)
                        .attr("d", d3.line()
                            .x(function (d) { return x(new Date(d.datetime)) })
                            .y(function (d) {
                                if (d.value > 100) return y0(100);
                                else if (d.value < 0) return y0(0);
                                else return y0(d.value);
                            })
                        )

                    svg.append("path")
                        .datum(chart2)
                        .attr("fill", "none")
                        .attr("stroke", "red")
                        .attr("stroke-width", 1)
                        .attr("d", d3.line()
                            .x(function (d) { return x(new Date(d.datetime)) })
                            .y(function (d) {
                                if (d.value > 100) return y0(100);
                                else if (d.value < 0) return y0(0);
                                else return y0(d.value);

                            })
                        )


                    svg.append("path")
                        .datum(chart3)
                        .attr("fill", "none")
                        .attr("stroke", "black")
                        .attr("stroke-width", 1)
                        .attr("d", d3.line()
                            .x(function (d) { return x(new Date(d.datetime)) })
                            .y(function (d) {
                                if (d.value > 100) return y0(100);
                                else if (d.value < 0) return y0(0);
                                else return y0(d.value);

                            })
                        )

                    if (chart4) {
                        svg.append("path")
                            .datum(chart4)
                            .attr("fill", "none")
                            .attr("stroke", "green")
                            .attr("stroke-width", 1)
                            .attr("d", d3.line()
                                .x(function (d) { return x(new Date(d.datetime)) })
                                .y(function (d) {
                                    if (d.value > 100) return y0(100);
                                    else if (d.value < 0) return y0(0);
                                    else return y0(d.value);

                                })
                            )
                    }

                    // References
                    if (type === 'INJ') {
                        svg.append("circle")
                            .attr("cy", -325)
                            .attr("cx", 15)
                            .attr("fill", "blue")
                            .attr("r", 6)

                        svg.append("text")
                            .attr("y", -320)
                            .attr("x", 70)
                            .text("North Carbon")

                        svg.append("circle")
                            .attr("cy", -325)
                            .attr("cx", 130)
                            .attr("fill", "red")
                            .attr("r", 6)

                        svg.append("text")
                            .attr("y", -320)
                            .attr("x", 190)
                            .text("South Carbon")

                        svg.append("circle")
                            .attr("cy", -325)
                            .attr("cx", 250)
                            .attr("fill", "black")
                            .attr("r", 6)

                        svg.append("text")
                            .attr("y", -320)
                            .attr("x", 310)
                            .text("LMF Lime")

                    } else if (type === 'SOUTH') {
                        svg.append("circle")
                            .attr("cy", -325)
                            .attr("cx", 15)
                            .attr("fill", "blue")
                            .attr("r", 6)

                        svg.append("text")
                            .attr("y", -320)
                            .attr("x", 70)
                            .text("Charge Carbon")

                        svg.append("circle")
                            .attr("cy", -325)
                            .attr("cx", 130)
                            .attr("fill", "red")
                            .attr("r", 6)

                        svg.append("text")
                            .attr("y", -320)
                            .attr("x", 190)
                            .text("HiCal")

                        svg.append("circle")
                            .attr("cy", -325)
                            .attr("cx", 250)
                            .attr("fill", "black")
                            .attr("r", 6)

                        svg.append("text")
                            .attr("y", -320)
                            .attr("x", 310)
                            .text("Dolo 1")

                        svg.append("circle")
                            .attr("cy", -325)
                            .attr("cx", 370)
                            .attr("fill", "green")
                            .attr("r", 6)

                        svg.append("text")
                            .attr("y", -320)
                            .attr("x", 430)
                            .text("Dolo 2")
                    } else {
                        svg.append("circle")
                            .attr("cy", -325)
                            .attr("cx", 15)
                            .attr("fill", "blue")
                            .attr("r", 6)

                        svg.append("text")
                            .attr("y", -320)
                            .attr("x", 70)
                            .text("Charge Carbon")

                        svg.append("circle")
                            .attr("cy", -325)
                            .attr("cx", 130)
                            .attr("fill", "red")
                            .attr("r", 6)

                        svg.append("text")
                            .attr("y", -320)
                            .attr("x", 190)
                            .text("HiCal")

                        svg.append("circle")
                            .attr("cy", -325)
                            .attr("cx", 250)
                            .attr("fill", "black")
                            .attr("r", 6)

                        svg.append("text")
                            .attr("y", -320)
                            .attr("x", 310)
                            .text("Dolo 1")

                        svg.append("circle")
                            .attr("cy", -325)
                            .attr("cx", 370)
                            .attr("fill", "green")
                            .attr("r", 6)

                        svg.append("text")
                            .attr("y", -320)
                            .attr("x", 430)
                            .text("Dolo 2")
                    }




                }

            }

            , exportToExcel: function () {
                var that = this,
                    params = this.model.toJSON();
                this.setExportButtonExporting(true);
                var params = [
                    { Name: '@timeZoneCode', Type: 'CHAR(10)', Value: app.models.user.get('timezoneCode') },
                    { Name: '@start', Type: 'DATETIME', Value: this.model.get('startDatetime') },
                    { Name: '@end', Type: 'DATETIME', Value: this.model.get('endDatetime') },
                    { Name: '@excelExport', Type: 'BIT', Value: true, },
                ];
                var QP = new QueryParameters();
                _.each(params, function (qpParams) {
                    QP.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });


                var data = {
                    Data: [],
                    ConnectionStringName: 'APP',
                    ExportMethod: 3,
                    FileName: 'Silos-Report',
                    TemplateFileFullPath: 'generic.xls',
                    SQLDataSources: [
                        {
                            Name: 'data',
                            DatabaseParameters: {
                                DBEngine: 'SQLSERVER',
                                Procedure: app.DatabaseNames.MES + '.MES.GetSilosReport',
                                QueryParameters: QP,
                            },
                        },
                    ]
                };

                /* -------------------------------------------------------- 1st Table ------------------------------------------------------------ */
                data.Data.push({
                    SheetName: 'South Flux Silos',
                    RowsData: [{
                        CellsData:
                            [
                                { Column: 'A', Value: 'Date' },
                                { Column: 'B', Value: 'Charge Carbon' },
                                { Column: 'C', Value: 'HiCal' },
                                { Column: 'D', Value: 'Dolo 1' },
                                { Column: 'E', Value: 'Dolo 2' },

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

                data.Data.push({
                    SheetName: 'South Flux Silos',
                    RowsData: [],
                    StartRowIndex: 2,
                    DataSourceName: 'data',
                    DataSourceTableIndex: 0,
                    SQLCellsData:
                        [
                            { ExcelColumnName: 'A', SQLDataColumnName: 'Date', DataType: 'String' },
                            { ExcelColumnName: 'B', SQLDataColumnName: 'ChargeCarbon', DataType: 'String' },
                            { ExcelColumnName: 'C', SQLDataColumnName: 'HiCal', DataType: 'String' },
                            { ExcelColumnName: 'D', SQLDataColumnName: 'Dolo1', DataType: 'String' },
                            { ExcelColumnName: 'E', SQLDataColumnName: 'Dolo2', DataType: 'String' },

                        ],
                });


                data.Data.push({
                    SheetName: 'North Flux Silos',
                    RowsData: [{
                        CellsData:
                            [

                                { Column: 'A', Value: 'Date' },
                                { Column: 'B', Value: 'Charge Carbon' },
                                { Column: 'C', Value: 'HiCal' },
                                { Column: 'D', Value: 'Dolo 1' },
                                { Column: 'E', Value: 'Dolo 2' },

                            ],
                    }],
                    StartRowIndex: 8,
                });

                data.Data.push({
                    SheetName: 'North Flux Silos',
                    RowsData: [],
                    StartRowIndex: 9,
                    DataSourceName: 'data',
                    DataSourceTableIndex: 1,
                    SQLCellsData:
                        [
                            { ExcelColumnName: 'A', SQLDataColumnName: 'Date', DataType: 'String' },
                            { ExcelColumnName: 'B', SQLDataColumnName: 'ChargeCarbon', DataType: 'String' },
                            { ExcelColumnName: 'C', SQLDataColumnName: 'HiCal', DataType: 'String' },
                            { ExcelColumnName: 'D', SQLDataColumnName: 'Dolo1', DataType: 'String' },
                            { ExcelColumnName: 'E', SQLDataColumnName: 'Dolo2', DataType: 'String' },

                        ],
                });


                //Inj
                data.Data.push({
                    SheetName: 'EAF Injection and LMF Lime',
                    RowsData: [{
                        CellsData:
                            [
                                { Column: 'A', Value: 'Date' },
                                { Column: 'B', Value: 'North Carbon' },
                                { Column: 'C', Value: 'South Carbon' },
                                { Column: 'D', Value: 'LMF Lime' },

                            ],
                    }],
                    StartRowIndex: 8,
                });

                data.Data.push({
                    SheetName: 'EAF Injection and LMF Lime',
                    RowsData: [],
                    StartRowIndex: 9,
                    DataSourceName: 'data',
                    DataSourceTableIndex: 2,
                    SQLCellsData:
                        [
                            { ExcelColumnName: 'A', SQLDataColumnName: 'Date', DataType: 'String' },
                            { ExcelColumnName: 'B', SQLDataColumnName: 'NorthDolo', DataType: 'String' },
                            { ExcelColumnName: 'C', SQLDataColumnName: 'SouthCarbon', DataType: 'String' },
                            { ExcelColumnName: 'D', SQLDataColumnName: 'LMFLime', 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.setExportButtonExporting(false);
                    },
                    function (resp) {
                        that.setExportButtonExporting(false);
                        console.error(resp);
                    }
                );
            }


            , setExportButtonExporting: function (val) {
                var btn_export = this.$el.find('.btn-export-to-excel');
                var export_state = btn_export.find('.excel-export-state');
                var loading_state = btn_export.find('.loading-state');

                if (val) {
                    export_state.css('display', 'none', 'important');
                    loading_state.removeClass('hide');

                    btn_export.attr('disabled', true);
                } else {
                    loading_state.addClass('hide');
                    export_state.css('display', 'inline-block', 'important');

                    btn_export.attr('disabled', 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();
                } catch (Error) { }
            }


        });



        Screen.Models.ItemSilos = Backbone.Epoxy.Model.extend({
            parse: function (obj) {
                var result = {
                    tagName: obj.tagName,
                    value: obj.Value,
                    datetime: new moment(obj.Datetime).format("MM-DD-YY HH:mm:ss"),
                };

                return result;
            },
        });

        Screen.Collections.ItemsSilos = Backbone.Collection.extend({
            fixedParameters: [],
            model: Screen.Models.ItemSilos,
            setDataColl: function (data) {
                var newColl,
                    that = this;
                newColl = _.map(data, that.model.prototype.parse);
                that.set(newColl).trigger('fetch', that, data);
            },

        });


        Screen.Collections.ItemsSouth = Backbone.Collection.extend({
            setDataColl: function (data) {
                var newColl,
                    that = this;
                newColl = data;
                that.set(newColl).trigger('fetch', that, data);
            },
        });
        Screen.Collections.ItemsNorth = Backbone.Collection.extend({
            setDataColl: function (data) {
                var newColl,
                    that = this;
                newColl = data;
                that.set(newColl).trigger('fetch', that, data);
            },
        });
        Screen.Collections.ItemsInj = Backbone.Collection.extend({
            setDataColl: function (data) {
                var newColl,
                    that = this;
                newColl = data;
                that.set(newColl).trigger('fetch', that, data);
            },
        });


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

    });