//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/infinator',
  'backgrid/moment-cell',
  'backgrid/grouped-columns',
  
  "js/jquery.floatThead/jquery.floatThead",
],
function (app, T, Backgrid, moment) {

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

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

            casterCode: 1,
            casters: [{ label: '1', value: 1 }, { label: '2', value: 2 }],

            crewId: null,
            crews: [{ label: 'A', value: 'A' }, { label: 'B', value: 'B' }, { label: 'C', value: 'C' }, { label: 'D', value: 'D' }],

            shiftId: null,
            shifts: [{ label: 'D', value: 1 }, { label: 'N', value: 2 }],


            strandId: null,
            strands: [{ label: '1', value: 1 }, { label: '2', value: 2 }, { label: '3', value: 3 }, { label: '4', value: 4 }],

            hasData: false,
            isLoading: false,

        },
        initialize: function () {
            this.itemsProducts = new Screen.Collections.ItemsCollection();
            this.itemsMeltOrder = new Screen.Collections.ItemsCollection();
            this.itemsTWILinks          = new Screen.Collections.ItemsCollection();
            this.itemsMeltOrderLinks    = new Screen.Collections.ItemsCollection();
            this.itemsEmailLinks        = new Screen.Collections.ItemsCollection();
        },
        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, };
                },
            },
        },
        

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

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.MES.GetForecastMeltOrders',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if (resp) {
                                that.itemsProducts.setDataColl(resp.Table);
                                that.itemsMeltOrder.setDataColl(resp.Table1);
                                that.itemsTWILinks.setDataColl(resp.Table2);
                                that.itemsMeltOrderLinks.setDataColl(resp.Table3);
                                that.itemsEmailLinks.setDataColl(resp.Table4);    
                              
                                that.trigger('fetch', resp);
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(new Error(resp.Message).stack);
                                else
                                    console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);

                                that.set({
                                    isLoading: false,
                                    hasData: false
                                });
                            }
                        }
                        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;
        },
    });


    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: 'forecast-melt-orders',
        id: 'forecast-melt-orders',
        title: 'Forecast Melt Orders',
        events: function () {
            return {
                'click #refreshBtn': this.refreshBtn_click,
            };
        },
        bindings: 'data-bind',
        bindingSources: null,
        grids: null,
        itemsColl: null,
        subviews: null,
        viewParams: null,

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

            if (!this.model)
                this.model = new Screen.Models.Main();

            this.bindEvents();
        },
        bindEvents: function () {
            this.listenTo(this.model, 'fetch', this.data_ready);

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

            this.viewParams = viewParams;

            var thatContainer = (this.options.container) ? this.options.container : container;
            this.options.container = thatContainer;

            //the screens have a custompath, so it has to be specified in the customPath variable that is
            //then sent to the template loader.
            var customPath = '/app/custom-screens/' + this.template + '/';

            T.render.call(
                this,
                this.template,
                function (tmp) {
                    if (!that.options.i18n) that.options.i18n = {};

                    app.getI18NJed(
                        that,
                        that.template,
                        function (i18nJED) {
                            //storing internationalization data
                            that.options.i18n[that.template] = i18nJED;

                            //loading the view and appeding it to the views's $el.
                            that.$el.html(tmp());

                            that.applyBindings();

                            that.$el.find('.input-date').datepicker();



                            var gridProducts = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed',
                                columns: [
                                    {
                                        name: 'Size',
                                        label: app.translate([that, app], 'Size'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell heat-row',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'HeatsRemaining',
                                        label: app.translate([that, app], 'Heats'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },                                
                                  
                                ],
                                header: Backgrid.Extension.GroupedHeader.extend({
                                    columnLayout:
                                        [
                                            {
                                                name: 'Heats Remaining By Size', children:
                                                    [
                                                        { name: 'Size' }
                                                        , { name: 'HeatsRemaining' }

                                                    ]

                                            },
                                        ],
                                    initialize: function (options) {
                                        Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                    },
                                    render: function () {
                                        var that = this;
                                        Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                        return this;
                                    },
                                }),
                                collection: that.model.itemsProducts,
                          
                               
                            });
                            that.$el.find('.products-grid-container').append(gridProducts.render().el);

                            var gridMeltOrders = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed',
                                columns: [
                                    {
                                        name: 'MeltOrder',
                                        label: app.translate([that, app], 'Melt Order'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell heat-row',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'Grade',
                                        label: app.translate([that, app], 'Grade'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'Size',
                                        label: app.translate([that, app], 'Size'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'HeatsOrdered',
                                        label: app.translate([that, app], 'Heats Ordered'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'HeatsCast',
                                        label: app.translate([that, app], 'Heats Cast'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'HeatsRemaining',
                                        label: app.translate([that, app], 'Heats Remaining'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell',
                                        }),
                                        editable: false,
                                    },

                                ],
                                header: Backgrid.Extension.GroupedHeader.extend({
                                    columnLayout:
                                        [
                                            {
                                                name: 'Available Melt Orders', children:
                                                    [
                                                        { name: 'MeltOrder' }
                                                        , { name: 'Grade' }
                                                        , { name: 'Size' }
                                                        , { name: 'HeatsOrdered' }
                                                        , { name: 'HeatsCast' }
                                                        , { name: 'HeatsRemaining' }

                                                    ]

                                            },
                                        ],
                                    initialize: function (options) {
                                        Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                    },
                                    render: function () {
                                        var that = this;
                                        Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                        return this;
                                    },
                                }),
                                collection: that.model.itemsMeltOrder,


                            });
                            that.$el.find('.melt-orders-grid-container').append(gridMeltOrders.render().el);


                            //Links
                            var gridTWI = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed',
                                columns: [
                                    {
                                        name: 'FileName',
                                        label: app.translate([that, app], 'Temporary Work Instructions'),
                                        cell: Backgrid.UriCell,
                                        editable: false,
                                    },

                                ],
                             
                                collection: that.model.itemsTWILinks,


                            });
                            that.$el.find('.twi-links-grid-container').append(gridTWI.render().el);


                            var gridMeltOrders = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed',
                                columns: [
                                    {
                                        name: 'FileName',
                                        label: app.translate([that, app], 'Melt Orders'),
                                        cell: Backgrid.UriCell,
                                        editable: false,
                                    },

                                ],

                                collection: that.model.itemsMeltOrderLinks,


                            });
                            that.$el.find('.melt-orders-links-grid-container').append(gridMeltOrders.render().el);

                            var gridEmails = new Backgrid.Grid({
                                className: 'backgrid table table-hover table-condensed',
                                columns: [
                                    {
                                        name: 'FileName',
                                        label: app.translate([that, app], 'E-Mails'),
                                        cell: Backgrid.UriCell,
                                        editable: false,
                                    },

                                ],

                                collection: that.model.itemsEmailLinks,


                            });
                            that.$el.find('.emails-links-grid-container').append(gridEmails.render().el);

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


                            that.refresh();
                            

                        },
                        true,
                        customPath
                    );
                },
                customPath
            );
        },
        data_ready: function () {
            try {
                var that = this;
                setTimeout(
                    function () {
                        that.model.set({
                            hasData: (that.model.itemsProducts.length > 0),
                            isLoading: false,
                        });
                        that.setURLClassGrid("twi-links", 'http://l2s-mlt-mes/External/TWI/');
                        that.setURLClassGrid("melt-orders-links",'http://l2s-mlt-mes/External/TWI/MeltOrders/');
                        that.setURLClassGrid("emails-links", 'http://l2s-mlt-mes/External/TWI/Emails/');
                       
                    },
                    100
                );
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },

        setURLClassGrid: function (id,urlRoute) {
            var gridElement = document.getElementById(id);
            var aTags = gridElement.getElementsByTagName("a");
           

            for (var i = 0; i < aTags.length; i++) {
                if (!aTags[i].innerHTML.includes('</b>'))
                    aTags[i].href = urlRoute + aTags[i].innerHTML;
            }
        },

        refresh: function () {
            this.model.set({
                hasData: false,
                isLoading: true,
            });
            this.model.fetchData();
        },
        refreshBtn_click: function (e) {
            this.refresh();   
        },

        //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.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) { }
        },
    });

    Screen.Collections.ItemsCollection = 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;
});