//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',
  'backgrid/grouped-columns',

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

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

    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {
            start: new moment().format('MM/DD/YYYY'),

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

            hasData: false,
            isLoading: false,
        },
    });

    Screen.Models.Item = Backbone.Epoxy.Model.extend({
        parse: function (obj,obj2) {
            var result = {
                HeatId: obj.HeatId,
            };
            _.each(obj2, function (obj,i) {
                result[obj.LocationName] = obj.Counter
                if (i == '0') {
                    result['TapTime'] = new moment(obj.TapTime);
                    result['ProductionDate'] = new moment(obj.ProductionDate);
                    result['Shift'] = obj.Shift;
                    result['TapTemperature'] = obj.TapTemperature;
                    result['TapChanges'] = obj.TapChanges;
                }
            });

            return result;
        },

    })

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

        fetch(params) {

            var that = this;
            var qp = new Core.Database.QueryParameters();

            qp.Add('@start', 'DATETIME', params.start)
            qp.Add('@furnaceCode', 'INT', params.furnaceCode == '-' ? null : params.furnaceCode);
            qp.Add('@timezoneCode', 'CHAR', app.models.user.get("timezoneCode"))

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

                            if ((resp) && (resp.Table)) {
                                var records = resp.Table,
                                    newColl;

                                var HeatIds = _.map(_.countBy(resp.Table, "HeatId"), function (value, key) {
                                    return { HeatId: key };
                                });

                                newColl = _.map(HeatIds, function (obj) {
                                    return that.model.prototype.parse(obj, _.where(resp.Table, { HeatId: obj.HeatId, }));
                                });
                                var method = 'set';
                                that[method](newColl, { from: 'fetch' })
                                   .trigger('fetch', that, records);
                               
                            }
                            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.Views.Main = Backbone.Epoxy.View.extend({
        template: 'eaf-components-history',
        id: 'eaf-components-history',
        title: 'EAF Components History',
        events: function () {
            return {
                'click #refreshBtn': this.refreshBtn_click,
            };
        },
        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 = new Screen.Collections.Items();
            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.items, 'fetch', this.items_fetched);
        
        },

        
        items_fetched: function (coll, resp) {  // Event received after collection is updated by collection.fetch
            try {
                this.model.set({
                            hasData: (this.items.length > 0),
                            isLoading: false,
                        });
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },


        render: function (container, urlParams) {
            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) {
                    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: 'HeatId',
                                    label: app.translate(that, 'item_Heat_col_label'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell HeatId',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'ProductionDate',
                                    label: app.translate(that, 'item_Production_Date_col_label'),
                                    cell: Backgrid.Extension.MomentCell.extend({
                                        className: 'moment-cell align-center-cell ProductionDate',
                                        modelFormat: 'YYYY-MM-DD',
                                        displayFormat: app.translate([that, app], 'MM/DD/YY'),
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'Shift',
                                    label: app.translate(that, 'item_Shift_col_label'),
                                    cell: Backgrid.StringCell.extend({
                                        className: 'string-cell align-center-cell ShiftId',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'TapTime',
                                    label: app.translate(that, 'item_Tap_Time_col_label'),
                                    cell: Backgrid.Extension.MomentCell.extend({
                                        className: 'moment-cell align-center-cell TapTime',
                                        modelFormat: 'YYYY-MM-DD HH:mm:ss.SSS',
                                        displayFormat: app.translate([that, app], 'MM/DD/YY') + ' HH:mm',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'TapTemperature',
                                    label: app.translate(that, 'item_Tap_Temperature_col_label'),
                                    cell: Backgrid.IntegerCell.extend({
                                        className: 'align-center-cell TapTemperature',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'Breast Electrode',
                                    label: app.translate(that, 'item_breast_electrode_col_label'),
                                    cell: Backgrid.IntegerCell.extend({
                                        className: 'align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'Bottom Inspected',
                                    label: app.translate(that, 'item_Bottom_Inspected_col_label'),
                                    cell: Backgrid.IntegerCell.extend({
                                        className: 'align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'Brick',
                                    label: app.translate(that, 'item_Brick_col_label'),
                                    cell: Backgrid.IntegerCell.extend({
                                        className: 'align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'Burner 1',
                                    label: app.translate(that, 'item_Burner_1_col_label'),
                                    cell: Backgrid.IntegerCell.extend({
                                        className: 'align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'Burner 2',
                                    label: app.translate(that, 'item_Burner_2_col_label'),
                                    cell: Backgrid.IntegerCell.extend({
                                        className: 'align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'Burner 3',
                                    label: app.translate(that, 'item_Burner_3_col_label'),
                                    cell: Backgrid.IntegerCell.extend({
                                        className: 'align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'Burner 4',
                                    label: app.translate(that, 'item_Burner_4_col_label'),
                                    cell: Backgrid.IntegerCell.extend({
                                        className: 'align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'Burner 5',
                                    label: app.translate(that, 'item_Burner_5_col_label'),
                                    cell: Backgrid.IntegerCell.extend({
                                        className: 'align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'Combustion Chamber',
                                    label: app.translate(that, 'item_Combustion_Chamber_col_label'),
                                    cell: Backgrid.IntegerCell.extend({
                                        className: 'align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'Delta',
                                    label: app.translate(that, 'item_Delta_col_label'),
                                    cell: Backgrid.IntegerCell.extend({
                                        className: 'align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'A Phase Electrode Arm ',
                                    label: app.translate(that, 'item_Electrode_Arm_1_col_label'),
                                    cell: Backgrid.IntegerCell.extend({
                                        className: 'align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'B Phase Electrode Arm ',
                                    label: app.translate(that, 'item_Electrode_Arm_2_col_label'),
                                    cell: Backgrid.IntegerCell.extend({
                                        className: 'align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'C Phase Electrode Arm ',
                                    label: app.translate(that, 'item_Electrode_Arm_3_col_label'),
                                    cell: Backgrid.IntegerCell.extend({
                                        className: 'align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'Lance',
                                    label: app.translate(that, 'item_Lance_col_label'),
                                    cell: Backgrid.IntegerCell.extend({
                                        className: 'align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'MOD',
                                    label: app.translate(that, 'item_MOD_Operations_col_label'),
                                    cell: Backgrid.IntegerCell.extend({
                                        className: 'align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'Roof ',
                                    label: app.translate(that, 'item_Roof_col_label'),
                                    cell: Backgrid.IntegerCell.extend({
                                        className: 'align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'Shell ',
                                    label: app.translate(that, 'item_Shell_col_label'),
                                    cell: Backgrid.IntegerCell.extend({
                                        className: 'align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'PACS',
                                    label: app.translate(that, 'item_Switch_Operations_col_label'),
                                    cell: Backgrid.IntegerCell.extend({
                                        className: 'align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'TapChanges',
                                    label: app.translate(that, 'item_Tap_Changes_col_label'),
                                    cell: Backgrid.IntegerCell.extend({
                                        className: 'align-center-cell',
                                    }),
                                    editable: false,
                                },
                                {
                                    name: 'Tap Hole',
                                    label: app.translate(that, 'item_Tap_Hole_col_label'),
                                    cell: Backgrid.IntegerCell.extend({
                                        className: 'align-center-cell',
                                    }),
                                    editable: false,
                                },                                
                            ];

                            var grid = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed production-table',
                                collection: that.items,
                                header: Backgrid.Extension.GroupedHeader.extend({
                                    columnLayout:
                                        [
                                            { name: 'Burner', children: [{ name: 'Burner 1' }, { name: 'Burner 2' }, { name: 'Burner 3' }, { name: 'Burner 4' }, { name: 'Burner 5' }] },
                                            { name: 'Phase Electrode Arm', children: [{ name: 'A Phase Electrode Arm ' }, { name: 'B Phase Electrode Arm ' }, { name: 'C Phase Electrode Arm ' }] },
                                        ],

                                    initialize: function (options) {
                                        Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                        this.listenTo(this.collection, 'backgrid:sort', this.collection_backgrid_sort);
                                    },

                                }),
                                columns: columns,


                            });

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

                            //appending view to the main container
                            that.append(thatContainer, that.$el);


                            var fixedParams = _.extend({}, urlParams);
                            if (fixedParams.start)
                                fixedParams.start = new moment(urlParams.start, 'YYYYMMDD').format('MM/DD/YYYY');
                            if (fixedParams.furnaceCode)
                                fixedParams.furnaceCode = fixedParams.furnaceCode != '-' ? fixedParams.furnaceCode : '-';

                            that.model.set(fixedParams);

                            that.refresh();


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


        refresh: function () {

            params = this.model.toJSON();
            
            this.model.set('isLoading', true);
            this.items.fetch({
                furnaceCode: params.furnaceCode,
                start: params.start,
            });

        },

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

                app.router.navigate(
                    app.router.resolveURL(
                        app.router.currentModule,
                            {
                                start: new moment(params.start, "MM/DD/YYYY").format("YYYYMMDD"),
                                furnaceCode: params.furnaceCode,
                            }
                            ,
                        false
                    ),
                    { trigger: false, }
                );

                this.refresh();

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

    });

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