//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',
  'backgrid/moment-cell',
  'highcharts'

],
function (app, T, Backgrid, moment) {

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

    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {
            start: new moment().subtract(7, 'd').format('YYYY-MM-DD'),
            end: new moment().format('YYYY-MM-DD'),

            furnaceCode: 'A',
            furnaces: [{ label: 'A', value: 1 }, { label: 'B', value: 2 }],

            hasData: false,
            isLoading: false,

            items: [[], [], [], [], [], []],
        },
        computeds: {
            start$: {
                deps: ['start'],
                get: function (value) {
                    return value;
                },
                set: function (value) {
                    return { start: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                },
            },
            end$: {
                deps: ['end'],
                get: function (value) {
                    return value;
                },
                set: function (value) {
                    return { end: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                },
            }
        },

        fetch(params,callback) {
      
            var qp = new Core.Database.QueryParameters();
            // optional parameters
            if (params.furnaceCode) {
                qp.Add('@furnaceCode', 'INT', params.furnaceCode)
            }
            // mandatory parameters
            qp.Add('@start', 'DATE', params.start)
            qp.Add('@end', 'DATE', params.end)

            console.info('fetch ' + params.start + ',' + params.end + ',' + params.furnaceCode);

            var model = this;

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

                            if (resp && resp.Table && resp.Table1 && resp.Table2) {
                                var items = model.get('items')

                                var records1 = _.map(resp.Table,  items[0].model.prototype.parse);
                                var records2 = _.map(resp.Table1, items[0].model.prototype.parse);
                                var records3 = _.map(resp.Table2, items[0].model.prototype.parse);
                                
                                items[0]['set'](records1, { from: 'fetch' }).trigger('fetch', items[0], records1);
                                items[1]['set'](records2, { from: 'fetch' }).trigger('fetch', items[1], records2);
                                items[2]['set'](records3, { from: 'fetch' }).trigger('fetch', items[2], records3);

                                callback(model);
                            }
                            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); }
                    },
                    Secured: true,
                },
                app.ConnectionStrings.app
            );

            return this;
        }
    });

    Screen.Models.Item = Backbone.Epoxy.Model.extend({
        defaults: {
        },
        parse: function (obj) {

            var item = {};
            for (var key in obj) {

                if (  // if it is a Date
                    (typeof obj[key] === 'string' || obj[key] instanceof String)
                    && obj[key].startsWith('/Date')) {
                    item[key] = new moment(obj[key]);
                }
                else {
                    item[key] = obj[key];
                }
            }
            return item;
        }
    });

    Screen.Collections.Items = Backbone.Collection.extend({
        model: Screen.Models.Item,
        chartArray : function()
        {
            return this.items;
        }
    });


    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: 'eaf-electrodes-report',
        id: 'eaf-electrodes-report',
        title: 'EAF Electrodes Report',
        events: function () {
            return {
                'click #refreshBtn': this.refreshBtn_click,
                "click .btn-export-to-excel": this.exportToExcel,
            };
        },
        bindings: 'data-bind',
        bindingSources: null,  //?
        

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

            var that = this;
            this.model = new Screen.Models.Main();
            this.items = this.model.get('items');
            this.items[0] = new Screen.Collections.Items();
            this.items[1] = new Screen.Collections.Items();
            this.items[2] = new Screen.Collections.Items();
        },


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

            // Get URL parameters passed from router.js and store them in Model
            console.info('render start:' + urlParams.start + ',' + urlParams.end + ',' + urlParams.furnaceCode);

            if (urlParams.start)
                that.model.set('start', new moment(urlParams.start, 'YYYYMMDD').format('YYYY-MM-DD'));

            if (urlParams.end)
                that.model.set('end', new moment(urlParams.end, 'YYYYMMDD').format('YYYY-MM-DD'));

            if (urlParams.furnaceCode)
                that.model.set('furnaceCode', (urlParams.furnaceCode != '-' && urlParams.furnaceCode != null) ? parseInt(urlParams.furnaceCode, 10) : null);


            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 columns = [
                                {
                                    name: 'ProductionDate',
                                    label: app.translate([that, app], 'ProductionDate'),
                                    cell: Backgrid.Extension.MomentCell.extend({
                                        displayFormat: "ddd, MM/DD/YYYY ",
                                        className: 'align-center-cell'
                                    }),
                                    editable: false
                                },
                                {
                                    name: 'ShiftId',
                                    label: app.translate([that, app], 'Shift'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'align-center-cell'
                                    }),
                                    editable: false
                                },
                                {
                                    name: 'CrewId',
                                    label: app.translate([that, app], 'Crew'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'align-center-cell'
                                    }),
                                    editable: false
                                },
                                {
                                    name: 'HeatId',
                                    label: app.translate([that, app], 'HeatId'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'align-center-cell'
                                    }),
                                    editable: false
                                },
                                {
                                    name: 'HeatsBetweenChanges',
                                    label: app.translate([that, app], 'HeatsBetweenChanges'),
                                    cell: Backgrid.IntegerCell.extend({
                                        className: 'align-center-cell'
                                    }),
                                    editable: false
                                },
                            ];
                            
                            var styledRow = Backgrid.Row.extend({
                                render: function () {
                                    Backgrid.Row.prototype.render.call(this)
                                    if (this.model.get('HeatId') == 'Average' ) {
                                        this.$el.addClass('average')
                                    } else {
                                        this.$el.removeClass('average')
                                    }
                                    return this
                                }
                            })


                            var grid1 = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed production-table',
                                collection: that.items[0],
                                columns: columns,
                                row: styledRow,
                            });
                            var grid2 = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed production-table',
                                collection: that.items[1],
                                columns: columns,
                                row: styledRow,
                            });
                            var grid3 = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed production-table',
                                collection: that.items[2],
                                columns: columns,
                                row: styledRow,
                            });

                            //container.append(grid.render().el);
                            that.$el.find('.grid-container1').append(grid1.render().el);
                            that.$el.find('.grid-container2').append(grid2.render().el);
                            that.$el.find('.grid-container3').append(grid3.render().el);
                           

                            //appending view to the main container
                            that.append(thatContainer, that.$el);
                            that.chart = that.createChart('chart');
                                                       
                            that.refresh();

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

        refreshChart: function(model)
        {
            var items = model.get('items');
            console.log(items)
            
            
            that.chart.series[0].setData(items[0].map(function (item) { return ['A' , item.get('HeatsBetweenChanges')]; }));
            that.chart.series[1].setData(items[1].map(function (item) { return ['B' , item.get('HeatsBetweenChanges')]; }));
            that.chart.series[2].setData(items[2].map(function (item) { return ['C' , item.get('HeatsBetweenChanges')]; }));
            

            that.chart.series[3].setData([['A' , items[0].at(0).get('HeatsBetweenChanges')]]);
            that.chart.series[4].setData([['B' , items[1].at(0).get('HeatsBetweenChanges')]]);
            that.chart.series[5].setData([['C' , items[2].at(0).get('HeatsBetweenChanges')]]);
        },

        refresh: function () {

            params = this.model.toJSON();
            
            console.info('refresh : start:' + params.start + ',' + params.end + ',' + params.furnaceCode);
            // this.model.set('isLoading', true);
            params.isLoading = true;
            that = this
            this.model.fetch(params, this.refreshChart);
           

        },

        refreshBtn_click: function (e) {
            try {
                var params = this.model.toJSON();
                console.info('button click ' + params.start + ',' + params.end + ',' + params.furnaceCode);

                app.router.navigate(
                    app.router.resolveURL(
                        app.router.currentModule,
                            {
                                start: new moment(params.start, 'YYYY-MM-DD').format('YYYYMMDD'),
                                end: new moment(params.end, 'YYYY-MM-DD').format('YYYYMMDD'),
                                furnaceCode: (params.furnaceCode == null || params.furnaceCode == "") ? '-' : params.furnaceCode,
                            }
                            ,
                        false
                    ),
                    { trigger: false, }
                );

                this.refresh();

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

        exportToExcel: function () {
            var that = this,
                  params = this.model.toJSON();

		console.log("params",params);
                var params = [
                    { Name: '@furnaceCode', Type: 'INT', Value: params.furnaceCode, },
                    { Name: '@start', Type: 'DATETIME', Value: params.start, },
                    { Name: '@end', Type: 'DATETIME', Value: params.end, },
                ];
                

            var qp = new QueryParameters();

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

            var cellsData = [
			{ Column: 'A', Value: 'ProductionDate' },
                                { Column: 'B', Value: 'Shift' },
                                { Column: 'C', Value: 'Crew' },
                                { Column: 'D', Value: 'HeatName' },
                                { Column: 'E', Value: 'HeatsBetweenChanges' },

                           
            ];             

            var SQLCellsData= [
                { ExcelColumnName: 'A', SQLDataColumnName: 'ProductionDate', DataType: 'String' },
                            { ExcelColumnName: 'B', SQLDataColumnName: 'ShiftId', DataType: 'String' },
                            { ExcelColumnName: 'C', SQLDataColumnName: 'CrewId', DataType: 'String' },
                            { ExcelColumnName: 'D', SQLDataColumnName: 'HeatId', DataType: 'String' },
                            { ExcelColumnName: 'E', SQLDataColumnName: 'HeatsBetweenChanges', DataType: 'String' },
            ];


            Core.Export.Excel({
                Data: [
                    {
                        SheetName: 'Phase A',
                        RowsData: [{
                            CellsData: cellsData
                        }],
                        StartRowIndex: 1,
                    },
                    {
                        SheetName: 'Phase A',
                        RowsData: [],
                        StartRowIndex: 2,
                        DataSourceName: 'data',
                        DataSourceTableIndex: 0,
                        SQLCellsData: SQLCellsData
                    },
		            {
                        SheetName: 'Phase B',
                        RowsData: [{
                            CellsData: cellsData
                        }],
                        StartRowIndex: 1,
                    },
                    {
                        SheetName: 'Phase B',
                        RowsData: [],
                        StartRowIndex: 2,
                        DataSourceName: 'data',
                        DataSourceTableIndex: 1,
                        SQLCellsData: SQLCellsData
                    },
		            {
                        SheetName: 'Phase C',
                        RowsData: [{
                            CellsData: cellsData
                        }],
                        StartRowIndex: 1,
                    },
                    {
                        SheetName: 'Phase C',
                        RowsData: [],
                        StartRowIndex: 2,
                        DataSourceName: 'data',
                        DataSourceTableIndex: 2,
                        SQLCellsData: SQLCellsData
                    }
                ],
                ConnectionStringName: 'APP',
                ExportMethod: 3,
                FileName: 'EAF-Electrodes',
                TemplateFileFullPath: 'generic.xls',
                SQLDataSources: [
                    {
                        Name: 'data',
                        DatabaseParameters: {
                            DBEngine: 'SQLSERVER',
                            Procedure: app.DatabaseNames.MES + '.EAF.GetElectrodesReportWeb',
                            QueryParameters: qp,
                        },
                    },
                ]
            },
            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); }
            }, function (resp) {
                console.error(resp);
            });

        },

        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 () {
      
        },
        stopAutoRefresh: function () {
      
        },

        createChart: function (el)
            {
            // create events to redraw
            this.items1

            return new Highcharts.chart(el, {
                chart: {
                    type: 'scatter',
                    zoomType: 'xy'
                },
                title: {
                    text: 'Heats Between Electrode Changes'
                },
                subtitle: {
                    text: '-'
                },
                xAxis: {
                    title: {
                        enabled: true,
                        text: 'Phase'
                    },
                    startOnTick: true,
                    endOnTick: true,
                    showLastLabel: true,
                    type: 'category',
                    categories: ['A','B','C']
                },
                yAxis: {
                    title: {
                        text: 'Heats'
                    }
                },
               
                plotOptions: {
                    scatter: {
                        marker: {
                            symbol: 'circle',
                            radius: 2,
                            states: {
                                hover: {
                                    enabled: true,
                                    lineColor: 'rgb(100,100,100)'
                                }
                            }
                        },
                        states: {
                            hover: {
                                marker: {
                                    enabled: false
                                }
                            }
                        },
                        tooltip: {
                            headerFormat: '<b>{series.name}</b><br>',
                            pointFormat: '{point.category} Phase, {point.y} Heats '
                        }
                    }
                },
                series: [
                    {
                        name: 'Phase A',
                        color: 'rgba(223, 23, 23, .7)',
                        data: []
                    },
                    {
                        name: 'Phase B',
                        color: 'rgba(23, 223, 23, .7)',
                        data: []
                    },
                    {
                        name: 'Phase C',
                        color: 'rgba(23, 23, 223, .7)',
                        data: []
                    }
                    ,
                    {
                        name: 'Avg A',
                        color: 'rgba(223 , 23, 23, .8)',
                        data: [],
                        marker: { radius: 6 }
                    },
                    {
                        name: 'Avg B',
                        color: 'rgba(23, 223 , 23, .8)',
                        data: [],
                        marker: { radius: 6 }
                    },
                    {
                        name: 'Avg C',
                        color: 'rgba(23, 23, 223, .8)',
                        data: [],
                        marker: { radius: 6 }
                    }
                ]
            });
        }
});




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