//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'

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

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

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

            ladleId: 1,
            ladles: [{ label: 'Ladle 1', value: 1 }, { label: 'Ladle 2', value: 2 }, { label: 'Ladle 3', value: 3 }, { label: 'Ladle 4', value: 4 }
                , { label: 'Ladle 5', value: 5 }, { label: 'Ladle 6', value: 6 }, { label: 'Ladle 7', value: 7 }, { label: 'Ladle 8', value: 8 }
                , { label: 'Ladle 9', value: 9 }, { label: 'Ladle 10', value: 10 }, { label: 'Ladle 11', value: 11 }, { label: 'Ladle 12', value: 12 }
                , { label: 'Ladle 13', value: 13 }, { label: 'Ladle 14', value: 14 }],

            hasData: false,
            isLoading: false,
        },
        computeds: {
            start$: {
                deps: ['start'],
                get: function (value) {
                    return value;
                },
                set: function (value) {
                    return { start: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                },
            },
            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, };
                },
            },


        },
        fetchLadles: function () {
            var that = this;
            Core.Json.CallProcedure(
              app.DatabaseNames.MES + '.LAD.GetLadles',
              null,
              {
                  onSuccess: function (resp) {
                      try {

                          if ((resp) && (resp.Table)) {

                              var records = _.map(resp.Table, function (item) { return { label: item.Name, value: item.Id } });
                              records.push({ label: "All Ladles", value: -1 });

                              that.set('ladles',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,
                  async: false,
              },
              app.ConnectionStrings.app
          );
        },
    });

    Screen.Models.Item = Backbone.Epoxy.Model.extend({
        defaults: {
            HeatId: null,
            TapTime: new moment(),
        },
        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,

        fetch(params) {

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

            // optional parameters
            if (params.ladleId) {
                qp.Add('@ladleId', 'INT', params.ladleId)
            }

            // mandatory parameters
            qp.Add('@start', 'DATE', params.start)
            qp.Add('@end', 'DATE', params.end)

            // that.isFetching = true;  //?
            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.LAD.GetLadleEquipmentHistory',
                qp,
                {
                    onSuccess: function (resp) {
                        try {

                            if ((resp) && (resp.Table)) {

                                var records = resp.Table,
                                    newColl;

                                newColl = _.map(records, that.model.prototype.parse);

                                var method = 'set';
                                that[method](newColl, { from: 'fetch' })
                                   .trigger('fetch', that, records);

                                //that.isFetching = false;?
                            }
                            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: 'ladle-history',
        id: 'ladle-history',
        title: 'ladle-history',
        events: function () {
            return {
                'click #refreshBtn': this.refreshBtn_click,
                'click #ladleWallBtn': this.ladleWallBtn_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 = new Screen.Collections.Items();

            this.model.fetchLadles();

            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);
            this.listenTo(this.model, 'change:start change:end change:ladleId', this.model_changed);
        }
    , model_changed: function (model) { // Event received after any change on the model parameters
        try {
            app.router.navigate(
                app.router.resolveURL(
                    app.router.currentModule,
                        {
                            start: new moment(model.get('start'), 'YYYY-MM-DD').format('YYYYMMDD'),
                            end: new moment(model.get('end'), 'YYYY-MM-DD').format('YYYYMMDD'),
                            ladleId: (model.get('ladleId') == null || model.get('ladleId') == "") ? '-' : model.get('ladleId'),
                        }
                        ,
                    false
                ),
                { trigger: false, }
            );
        }
        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
    }

    , items_fetched: function (coll, resp) {  // Event received after collection is updated by collection.fetch
        try {
            var that = this;

            setTimeout(  // - why?
                function () {
                    that.model.set({
                        hasData: (that.items.length > 0),
                        isLoading: false,
                    });
                },
                100
            );
        }
        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
    }

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

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

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

            if (urlParams.ladleId)
                that.model.set('ladleId', (urlParams.ladleId != '-' && urlParams.ladleId != null) ? parseInt(urlParams.ladleId, 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 counters = [
                                , 'LadleSlideGate'
                                , 'MountingPlate'
                                , 'PlateAssembly'
                                , 'UpperNozzle'
                                , 'WorkingLining'
                                , 'PorousPlugNorth'
                                , 'PorousPlugSouth'
                            ];

                            var cols = _.map(counters, function (x) {
                                return {
                                    name: x,
                                    label: app.translate([that, app], x),
                                    cell: Backgrid.IntegerCell.extend({
                                        className: 'align-center-cell'
                                    }),
                                    editable: false,
                                }
                            }
                            );


                            var columns = _.union([
                                     {

                                        name: 'LadleId',

                                        label: app.translate([that, app], 'Ladle'),

                                        cell: Backgrid.StringCell.extend({

                                            className: 'string-cell align-center-cell ',

                                        }),

                                        editable: false,

                                    },
                                     {
                                         name: 'HeatId',
                                         label: app.translate([that, app], 'Heat Id'),
                                         cell: Backgrid.StringCell.extend({
                                             className: 'string-cell align-center-cell ',
                                         }),
                                         editable: false,
                                     },

                                      {
                                          name: 'TapTime',
                                          label: app.translate([that, app], 'Tap Time'),
                                          cell: Backgrid.Extension.MomentCell.extend({
                                              className: 'moment-cell align-center-cell ',
                                              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, app], 'Tap Temperature'),
                                           cell: Backgrid.IntegerCell.extend({
                                               className: 'align-center-cell ',
                                           }),
                                           editable: false,
                                       },
                                        {
                                            name: 'SteelWeight',
                                            label: app.translate([that, app], 'Steel Weight'),
                                            cell: Backgrid.IntegerCell.extend({
                                                className: 'align-center-cell ',
                                            }),
                                            editable: false,
                                        }
                            ], cols);

                            var coloredRow = Backgrid.Row.extend({
                                render: function () {
                                    Backgrid.Row.prototype.render.call(this)
                                    if (this.model.get('HeatId') == 'Last') {
                                        this.$el.addClass('last');
                                    } else {
                                        this.$el.removeClass('last');
                                    }

                                    if (this.model.get('HeatId') == 'Drain') {
                                        this.$el.addClass('drain');
                                    } else {
                                        this.$el.removeClass('drain');
                                    }
                                    return this
                                }
                            });


                            var grid = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed production-table',
                                collection: that.items,
                                columns: columns,
                                row: coloredRow,

                            });

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

                            that.refresh();


                        },
                        true,
                        customPath
                    );
                },
                customPath
            );
        },
         exportToExcel: function () {
                var that = this, p = this.model.toJSON();
                that.setExportButtonExporting(true);

                var params = [
                    { Name: '@start', Type: 'DATETIME', Value: p.start, },
                    { Name: '@end', Type: 'DATETIME', Value: p.end, },
                    { Name: '@LadleId', Type: 'INT', Value: (p.ladleId != null && p.ladleId !== '') ? p.ladleId : null, },
                ];
                var QP = new QueryParameters();

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

                var fileName = 'Ladle-Equipment-History_' +
                    moment(p.start, 'YYYY-MM-DD').format('YYYYMMDD') + '_' +
                    moment(p.end, 'YYYY-MM-DD').format('YYYYMMDD');

                var data = {
                    Data: [],
                    ConnectionStringName: 'APP',
                    ExportMethod: 3,
                    FileName: "Ladle-Equipment-History",
                    TemplateFileFullPath: 'generic.xls',
                    SQLDataSources: [{
                        Name: 'data',
                        DatabaseParameters: {
                            DBEngine: 'SQLSERVER',
                            Procedure: app.DatabaseNames.MES + '.LAD.GetLadleEquipmentHistory',
                            QueryParameters: QP
                        }
                    }]
                };

                // Header
                data.Data.push({
                    SheetName: 'Data',
                    RowsData: [{
                        CellsData: [
                            { Column: 'A', Value: 'LadleId' },
                            { Column: 'B', Value: 'HeatId' },
                            { Column: 'C', Value: 'TapTime' },
                            { Column: 'D', Value: 'TapTemperature' },
                            { Column: 'E', Value: 'SteelWeight' },
                            { Column: 'F', Value: 'LadleSlideGate' },
                            { Column: 'G', Value: 'MountingPlate' },
                            { Column: 'H', Value: 'PlateAssembly' },
                            { Column: 'I', Value: 'UpperNozzle' },
                            { Column: 'J', Value: 'WorkingLining' },
                            { Column: 'K', Value: 'PorousPlugNorth' },
                            { Column: 'L', Value: 'PorousPlugSouth' }
                        ]
                    }],
                    StartRowIndex: 1
                });

                // Mappings
                data.Data.push({
                    SheetName: 'Data',
                    RowsData: [],
                    StartRowIndex: 2,
                    DataSourceName: 'data',
                    DataSourceTableIndex: 0,
                    SQLCellsData: [
                        { ExcelColumnName: 'A', SQLDataColumnName: 'LadleId', DataType: 'String' },
                        { ExcelColumnName: 'B', SQLDataColumnName: 'HeatId', DataType: 'String' },
                        { ExcelColumnName: 'C', SQLDataColumnName: 'TapTime', DataType: 'String' },
                        { ExcelColumnName: 'D', SQLDataColumnName: 'TapTemperature', DataType: 'String' },
                        { ExcelColumnName: 'E', SQLDataColumnName: 'SteelWeight', DataType: 'String' },
                        { ExcelColumnName: 'F', SQLDataColumnName: 'LadleSlideGate', DataType: 'String' },
                        { ExcelColumnName: 'G', SQLDataColumnName: 'MountingPlate', DataType: 'String' },
                        { ExcelColumnName: 'H', SQLDataColumnName: 'PlateAssembly', DataType: 'String' },
                        { ExcelColumnName: 'I', SQLDataColumnName: 'UpperNozzle', DataType: 'String' },
                        { ExcelColumnName: 'J', SQLDataColumnName: 'WorkingLining', DataType: 'String' },
                        { ExcelColumnName: 'K', SQLDataColumnName: 'PorousPlugNorth', DataType: 'String' },
                        { ExcelColumnName: 'L', SQLDataColumnName: 'PorousPlugSouth', 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.model.refreshProcesses();
                        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);
                }
            },



        refresh: function () {

            params = this.model.toJSON();
            this.model.set('isLoading', true);
            this.items.fetch(params);

        },

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

                this.refresh();

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

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

                Backbone.history.navigate('!/ladle-wall-manager/', { trigger: true });

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



/*



                        */

