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

    'modules/modal2',
    'backgrid',
    'moment',
    'backgrid/moment-cell',
    'backgrid/grouped-columns',

    "js/jquery.floatThead/jquery.floatThead",
    'js/jquery.contextMenu/jquery.contextMenu',
],
    function (app, T, Modal, Backgrid, moment) {

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

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

                hasData: false,
                isLoading: true,

                heatColors: [],
                
                rowModel: [],
                contextMenuOption: null,
                
                grid: [],

                gridHeats: [],
                

            },            
            initialize: function () {
                this.itemsColl = new Screen.Collections.Items();
            },
            fetch: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters();

                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.CAS.RTCAS1GetHeats',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if ((resp) && (resp.Table)) {
                                    that.itemsColl.setDataColl(resp.Table);
                                    that.trigger('GetCaster1HeatsReady');
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        console.error(new Error(resp.Message).stack);
                                        app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 5000, });
                                        that.trigger('GetCaster1HeatsReady');
                                    }
                                    else {
                                        app.views.topMessages.showMessage('SERVER RESPONSE NOT VALID', { stay: 5000, });
                                        console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                    }
                                }
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        onFailure: function (resp) {
                            console.error(resp);
                        },
                        Secured: true,
                        Async: true,
                    },
                    app.ConnectionStrings.app
                );
                return this;
            },
            assignCasterProcessInPLC: function (params) {
                try {
                    var that = this;
                    qp = new Core.Database.QueryParameters();
                    this.fixedParameters = [
                        { Name: '@processId', Type: 'INT', Value: params.processId, },
                        { Name: '@heatId', Type: 'INT', Value: params.heatId, },
                    ];
                    _.each(this.fixedParameters, function (qpParams) {
                        qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                    });

                    Core.Json.CallProcedure(
                        app.DatabaseNames.MES + '.CAS.AssignCasterProcessInPLC',
                        qp,
                        {
                            onSuccess: function (resp) {
                                try {
                                    if (resp && !resp.Message) {
                                        app.views.topMessages.showMessage('Heat Assigned', { stay: 5000, });
                                        that.trigger('reassigned');
                                    }
                                    else {
                                        if ((resp) && (resp.Message)) {
                                            app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                            console.error(resp.Message);
                                        }
                                        else {
                                            app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                            console.error("Server response not valid.");
                                        }
                                    }
                                }
                                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                            },
                            onFailure: function (resp) {
                                console.error(resp);
                            },
                            Secured: true,
                            Async: false,
                        },
                        app.ConnectionStrings.app
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },

            unassing: function (params) {
                try {
                    var that = this;
                    qp = new Core.Database.QueryParameters();
                    this.fixedParameters = [
                        { Name: '@processId', Type: 'INT', Value: params.processId, },
                    ];

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

                    Core.Json.CallProcedure(
                        app.DatabaseNames.MES + '.CAS.UnassignCasterProcessMES',
                        qp,
                        {
                            onSuccess: function (resp) {
                                try {
                                    if (resp && !resp.Message) {
                                        app.views.topMessages.showMessage('Heat Unassigned', { stay: 5000, });
                                        that.trigger('reassigned');
                                    }
                                    else {
                                        if ((resp) && (resp.Message)) {
                                            app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                            console.error(resp.Message);
                                        }
                                        else {
                                            app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                            console.error("Server response not valid.");
                                        }
                                    }
                                }
                                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                            },
                            onFailure: function (resp) {
                                console.error(resp);
                            },
                            Secured: true,
                            Async: false,
                        },
                        app.ConnectionStrings.app
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            }
         
        });

        Screen.generateID = function (viewParams) {
            try {
                //if the viewparams change the view id, then evaluate the viewparams here
                //and return the appropiate id.refreshbtn
                return 'caster-heats-real-time';
            } catch (Error) { }
        }





        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'caster-heats-real-time',
            id: 'caster-heats-real-time',
            title: 'Caster 1 Heats Real Time',
            events: function () {
                return {
                    'click #BackToSupervisionScreen': this.BackToSupervisionScreen_click,
                };
            },

            bindings: 'data-bind',
            bindingSources: null,
            grids: null,
            subviews: null,
            viewParams: null,
          
            pauseTimer: false,
            pauseRealTime: false,
            
            currentModal: null,
            timeCounter: 0,
           
            acceptHeatModal: null,
            gridHeats: 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.templates = {
                };

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

                this.grids = {};
                this.bindingSources = {};
                this.subviews = {};

                this.autoRefresh = {
                    enabled: null
                    , toid: null
                    , every: 5 * 1000

                };
                this.bus = _.extend({}, Backbone.Events);
                this.bus.on("modalAcceptBtn", this.onModalAcceptBtn, this);
                this.bus.on("modalAcceptTrigger", this.onModalAcceptTrigger, this);

                this.bindEvents();
            },

            BackToSupervisionScreen_click: function () {
                app.router.navigate('!/caster-supervision/', { trigger: true });
            },
         
            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) {
                                that.options.i18n[that.template] = i18nJED;
                                that.$el.html(tmp());


                                that.applyBindings();


                                var gridHeats = new Backgrid.Grid({
                                    className: 'backgrid table table-hover table-condensed production-table',
                                    columns: [
                                        //MES.Heats
                                        {
                                            name: 'MES_HeatName',
                                            label: app.translate([that, app], 'Heat'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },

                                        {
                                            name: 'MES_MeltOrder',
                                            label: app.translate([that, app], 'Melt Order'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },

                                        {
                                            name: 'MES_Grade',
                                            label: app.translate([that, app], 'Grade'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'MES_Ladle',
                                            label: app.translate([that, app], 'Ladle'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },


                                        // CAS.Processes
                                        {
                                            name: 'Process_L1HeatName',
                                            label: app.translate([that, app], 'L1 Heat'),
                                            cell: Backgrid.StringCell.extend({
                                                className: function () {
                                                    var model = this.model.toJSON();
                                                    if (model.Process_Status === 'WRONG') return 'string-cell align-center-cell wrong';
                                                    else return 'string-cell align-center-cell';
                                                },
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'Process_LadleOpen',
                                            label: app.translate([that, app], 'Ladle Open'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },

                                        {
                                            name: 'Process_StartCast',
                                            label: app.translate([that, app], 'Start Cast'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },

                                        {
                                            name: 'Process_LadleClose',
                                            label: app.translate([that, app], 'Ladle Close'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },

                                        {
                                            name: 'Process_EndCast',
                                            label: app.translate([that, app], 'End Cast'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },
                                        //CAS.Products
                                        {
                                            name: 'Products_S1',
                                            label: app.translate([that, app], 'S1'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },

                                        {
                                            name: 'Products_S2',
                                            label: app.translate([that, app], 'S2'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },

                                        {
                                            name: 'Products_S3',
                                            label: app.translate([that, app], 'S3'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },

                                        {
                                            name: 'Products_S4',
                                            label: app.translate([that, app], 'S4'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },

                                        //LAD.Heats
                                        {
                                            name: 'LAD_HeatName',
                                            label: app.translate([that, app], 'Heat'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'LAD_Status',
                                            label: app.translate([that, app], 'Status'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'LAD_Ladle',
                                            label: app.translate([that, app], 'Ladle'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'LAD_Location',
                                            label: app.translate([that, app], 'Location'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },
                                      
                                        {
                                            name: 'LAD_LadleOpen',
                                            label: app.translate([that, app], 'Ladle Open'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'LAD_MeltOrder',
                                            label: app.translate([that, app], 'Melt Order'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },
                                        {
                                            name: 'LAD_Grade',
                                            label: app.translate([that, app], 'Grade'),
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell heat-row',
                                            }),
                                            editable: false,
                                        },
                                                                              
                                    ],
                                    header: Backgrid.Extension.GroupedHeader.extend({
                                        columnLayout:
                                            [
                                                {
                                                    name: 'MES Heats', children:                                                                 
                                                        [
                                                            { name: 'MES_HeatName' }
                                                            , { name: 'MES_MeltOrder' }
                                                            , { name: 'MES_Grade' }
                                                            , { name: 'MES_Ladle' }
                                                        ]   
                                                },
                                                {
                                                    name: 'CAS Processes', children:
                                                        [
                                                              { name: 'Process_L1HeatName' }
                                                            , { name: 'Process_LadleOpen' }
                                                            , { name: 'Process_StartCast' }
                                                            , { name: 'Process_LadleClose' }
                                                            , { name: 'Process_EndCast' }
                                                        ]
                                                },
                                                {
                                                    name: 'CAS Products', children:
                                                        [
                                                              { name: 'Products_S1' }
                                                            , { name: 'Products_S2' }
                                                            , { name: 'Products_S3' }
                                                            , { name: 'Products_S4' }
                                                        ]
                                                },
                                                {
                                                    name: 'LAD Heats', children:
                                                        [
                                                              { name: 'LAD_HeatName' }
                                                            , { name: 'LAD_Status' }
                                                            , { name: 'LAD_Ladle' }
                                                            , { name: 'LAD_Location' }
                                                            , { name: 'LAD_LadleOpen' }
                                                            , { name: 'LAD_MeltOrder' }
                                                            , { name: 'LAD_Grade' }
                                                        ]
                                                },

                                            ],
                                        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;
                                        },
                                    }),
                                    row: Backgrid.Row.extend({
                                        initialize: function (options) {
                                            Backgrid.Row.prototype.initialize.apply(this, arguments);
                                        },
                                        events: {
                                            contextmenu: 'onRightClick',
                                        },
                                        onRightClick: function (e) {
                                            e.preventDefault();
                                            var model = this.model.toJSON();

                                            var rowsView = that.model.get('gridHeats').body.rows;
                                            var newIndex = _.indexOf(rowsView, this);
                                            this.$el.addClass("onRightClickSelectedRow");

                                            that.model.set({
                                                rowModel: model,
                                                index: newIndex,
                                            });
                                        },

                                    }),
                                    collection: that.model.itemsColl,

                                });
                                that.$el.find('.processes-grid-container').append(gridHeats.render().el);

                                that.model.set({ gridHeats: gridHeats });
                                $.contextMenu('destroy');
                                $(function (obj) {
                                    $.contextMenu({
                                        selector: '.production-table',
                                        callback: function (key, options) {
                                            that.model.set({ contextMenuOption: key });
                                            that.contextMenuOptionPressed();
                                        },
                                        items: {                                          
                                            "opt-assign-heat": {
                                                name: "Assign Heat",
                                                icon: "edit",
                                                visible: true,
                                                disabled: function (key, opt) {
                                                    var model = that.model.get('rowModel');
                                                    if (model && model.Process_L1HeatName && model.Process_L1HeatName.includes('UNK')) return false;
                                                    else return true;
                                                }
                                            },     
                                            //"opt-unassign-heat": {
                                            //    name: "Unassign Heat",
                                            //    icon: "edit",
                                            //    visible: true,
                                            //    disabled: function (key, opt) {
                                            //        var model = that.model.get('rowModel');
                                            //        if (model.MESHeatId) return false;
                                            //        else return true;
                                            //    }
                                            //},   
                                            //"opt-create-heat": {
                                            //    name: "Create Heat",
                                            //    icon: "edit",
                                            //    visible: true,
                                            //},   
                                            //"opt-change-products": {
                                            //    name: "Change Products",
                                            //    icon: "edit",
                                            //    visible: true,
                                            //},  
                                        },
                                        events: {
                                            hide: function (options) {
                                                that.pauseRealTime = false;
                                                that.removeHighlightRow();
                                            },
                                            show: function () {
                                                that.pauseRealTime = true;
                                            }
                                        }
                                    });
                                });


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

                                that.startAutoRefresh();

                            },
                            true,
                            customPath
                        );
                    },
                    customPath
                );
            },
            //-------------------------------------//
            //-------- CONTEXT MENU OPTIONS -------//
            //-------------------------------------//

            contextMenuOptionPressed: function () {
                var that = this;
                rowModel = this.model.get('rowModel'),
                contextMenuOption = this.model.get('contextMenuOption');
                switch (contextMenuOption) {
                    case "opt-assign-heat":
                        this.openEditionModal(rowModel, false, rowModel.CASProcessId);
                        break;
                    case "opt-unassign-heat":                        
                        message = 'The Heat ' + rowModel.HeatName + ' will be unassigned. Do you want to continue ?'
                        modal = new Modal.Views.Main({
                            focusOk: false,
                            focusSelector: '#btn-cancel',
                            title: 'Unassign Heat Confirmation: ' + rowModel.HeatName,
                            message: message,
                            buttons_type: "CONTINUE-CANCEL",
                        });
                        this.listenToOnce(modal, "continue", function (modal) {
                            try {
                                that.model.unassing({
                                    processId: rowModel.CASProcessId,
                                });
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        });
                        modal.show();
                        break;
                }
            },

            onModalAcceptBtn: function (processId, heatId) {
                this.model.assignCasterProcessInPLC({
                    processId: processId,
                    heatId: heatId,
                })
            },
            bindEvents: function () {
                this.listenTo(this.model.itemsColl, 'fetch', this.processes_ready);
                this.listenTo(this.model, 'GetCaster1HeatsReady', this.GetCaster1HeatsReady_ready);
            },
          
            GetCaster1HeatsReady_ready: function () {
                var that = this;
                setTimeout(
                    function () {
                        that.model.set({ isLoading: false });
                        that.pauseTimer = false;
                    },
                    100
                );
            },

            //Auto refresh
            _refresh: function (opt) {
                if (this.autoRefresh.toid != null) {
                    clearTimeout(this.autoRefresh.toid);
                    this.autoRefresh.toid = null;
                }
                if (!this.pauseTimer) this.refresh();

                if (this.autoRefresh.enabled == true) {
                    var that = this;

                    this.autoRefresh.toid = setTimeout(
                        function () { that._refresh(); },
                        this.autoRefresh.every
                    );
                }
            },
            startAutoRefresh: function () {
                try {
                    if (this.autoRefresh.enabled !== true) {
                        var that = this;

                        if (this.autoRefresh.toid != null) {
                            clearTimeout(this.autoRefresh.toid);
                            this.autoRefresh.toid = null;
                        }

                        this.autoRefresh.enabled = true;

                        //use a timeout to execute the first refresh to return the handle to the start function caller.
                        //So when the caller finish it will do the first refresh.
                        this.autoRefresh.toid = setTimeout(
                            function () { that._refresh(); },
                            1
                        );
                    }
                } catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
            },
            stopAutoRefresh: function () {
                if (this.autoRefresh.toid != null) {
                    clearTimeout(this.autoRefresh.toid);
                    this.autoRefresh.toid = null;
                }
                this.autoRefresh.enabled = false;
            },

            refresh: function (viewParams) {
                if (this.currentModal) {
                    this.currentModal.hide();
                    this.currentModal = null;
                }

                if (!this.pauseRealTime) {
                    this.pauseTimer = true;
                    if (this.model.get('search') === '' && this.model.get('strandId') === '-') {
                        this.model.fetch({ products: false });
                    } else if (this.model.get('search') === '' && this.model.get('strandId') != '-') {
                        this.model.set({
                            strandId: '-',
                            search: '',
                        });
                        this.model.fetch({ products: true });
                    }
                    else {
                        this.model.fetch({ products: true });
                    }

                    this.timeCounter += 1;
                    if (this.timeCounter > 0) {
                        this.timeCounter = 0;
                    }


                }
            },
            onModalAcceptTrigger: function (obj) {
                this.model.fetch({ products: true });
            },




            //----------------------------------//
            //-------- Processes Ready -------//
            //----------------------------------//
            processes_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData: (that.model.itemsColl.length > 0),
                                isLoading: false,
                            });
                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },

           
            openEditionModal: function (model, unassign, processId) {
                var modal = new Screen.Views.AssignModal({
                    processId: processId,
                    row: model,
                    bus: this.bus,
                    unassign: unassign,
                });
                modal.show();
            },

            removeHighlightRow: function () {
                var previousIndex = this.model.get('index');
                var rowsViewHeats = this.model.get('gridHeats').body.rows;

                if (rowsViewHeats && rowsViewHeats[previousIndex] && rowsViewHeats[previousIndex].$el)
                    rowsViewHeats[previousIndex].$el.removeClass("onRightClickSelectedRow");

            },
           

            //-------------------------------------//
            //-------- 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;
                //If currentModal exists, hide it and erase it.
                if (this.currentModal) {
                    this.currentModal.hide();
                    this.currentModal = null;
                }
                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) { }
            },



        });




        /*------------------------------- */
        /*------------------------------- */
        /*------------------------------- */
        /*------------------------------- */
        /*------------------------------- */
        /*------------------------------- */

        Screen.Collections.Items = Backbone.Collection.extend({
            setDataColl: function (data) {
                this.set(data).trigger('fetch');
            },
        });

        /*------------------------------- */
        /*------------------------------- */
        /*------------------------------- */
        /*------------------------------- */
        /*------------------------------- */
        /*------------------------------- */
        /****** ASSIGN UNK HEATS ********/

        /*------------------------------- */
        /*------------------------------- */
        /*------------------------------- */
        /*------------------------------- */
        /*------------------------------- */
        /*------------------------------- */

        Screen.Collections.LastHeats = Backbone.Collection.extend({
            fetch: function (params) {
                var that = this;
                var qp = new Core.Database.QueryParameters();

                qp.Add('@processId', 'INT', params.processId);

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

                                if ((resp) && (resp.Table)) {
                                    newColl = resp.Table;
                                    that.set(newColl);
                                    that.trigger('fetch', that, newColl);

                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        console.error(new Error(resp.Message).stack);
                                        app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 5000, });
                                    }
                                    else {
                                        app.views.topMessages.showMessage('SERVER RESPONSE NOT VALID', { stay: 5000, });
                                        console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                    }
                                }
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        onFailure: function (resp) {
                            console.error(resp);
                        },
                        Secured: true,
                        Async: true,
                    },
                    app.ConnectionStrings.app
                );
                return this;
            },

        });



        //---------------------//
        //------ Assign -------//
        //---------------------//
        Screen.Models.AssignModal = Backbone.Epoxy.Model.extend({
            defaults: {
                errorMsg: '',
                processing: true,
                title: '',
                hasData: false,
                isLoading: true,
                index: null,

                selectedHeatId: null,
                currentProcessId: null,
                show_unassign_btn: false,
            },
        });
        Screen.Views.AssignModal = Backbone.Epoxy.View.extend({
            template: "caster-heats-real-time",
            id: "assign-heats",
            className: "modal modal-assign-heats hide fade",
            bindings: "data-bind",
            isCacheable: true,
            events: function () {
                return {
                    "click #acceptBtn": this.acceptBtn_click,
                    "click #cancelBtn": this.cancelBtn_click,
                    "click #unassignBtn": this.unassignBtn_click,
                    "submit form": this.form_submit,
                    "keypress": this.modal_keypress,
                    "show.bs.modal": this.modal_show,
                    "shown.bs.modal": this.modal_shown,
                    "hidden.bs.modal": this.modal_hidden,
                };
            },
            container: null,
            disposed: false,
            isRendered: false,
            preventDispose: false,
            visible: false,
            row: [],
            lastHeatsColl: [],
            grid: [],
            initialize: function (options) {
                _.extend(this, options);
                if (!this.model) {
                    this.model = new Screen.Models.AssignModal();
                }
                //this.row = options.row.toJSON();
                this.row = options.row;
                this.model.set({
                    currentProcessId: this.processId,
                    show_unassign_btn: false,
                    title: " Assign Caster Process " + this.row.HeatName
                });

                this.lastHeatsColl = new Screen.Collections.LastHeats();

                this.lastHeatsColl.fetch({
                    processId: this.processId
                });

                this.bus = options.bus;

                this.bindEvents();

                return this;
            },

            hide: function (preventDispose) {
                this.preventDispose = (preventDispose);

                this.$el.modal('hide');
            },
            render: function (container) {
                if (container)
                    this.container = container;

                var that = this;
                var customPath = '/app/custom-screens/' + this.template + '/';
                T.render.call(this, this.template, function (tmp) {
                    if (!that.i18n) that.i18n = {};
                    app.getI18NJed(that, that.template, function (i18nJED) {
                        that.i18n[that.template] = i18nJED;
                        that.$el.html(tmp(that.model.toJSON()));
                        that.applyBindings();

                        var columns = [
                            {
                                name: 'HeatName',
                                label: 'Heat',
                                cell: Backgrid.StringCell.extend({
                                    className: 'string-cell align-center-cell',
                                }),
                                editable: false,
                                sortable: false,
                            },
                            {
                                name: 'EndTap',
                                label: 'End Tap',
                                cell: Backgrid.StringCell.extend({
                                    className: 'string-cell align-center-cell',
                                }),
                                editable: false,
                                sortable: false,
                            },
                            {
                                name: 'GradeName',
                                label: 'Grade',
                                cell: Backgrid.StringCell.extend({
                                    className: 'string-cell align-center-cell',
                                }),
                                editable: false,
                                sortable: false,
                            },

                            {
                                name: 'MaterialSize',
                                label: 'Mold Size',
                                cell: Backgrid.StringCell.extend({
                                    className: 'string-cell align-center-cell',
                                }),
                                editable: false,
                                sortable: false,
                            },


                        ];
                        var grid = new Backgrid.Grid({
                            className: 'backgrid table table-hover table-condensed',
                            collection: that.lastHeatsColl,
                            columns: columns,
                            row: Backgrid.Row.extend({
                                initialize: function (options) {
                                    Backgrid.Row.prototype.initialize.apply(this, arguments);

                                },
                                events: {
                                    click: 'click',
                                },

                                click: function (e) {
                                    try {
                                        var previousIndex = that.model.get('index');

                                        if (!this.$el.hasClass("selectedItem")) {
                                            this.$el.addClass("selectedItem");
                                            that.model.set({ selectedHeatId: this.model.get('HeatId') });
                                        }
                                        var rowsView = that.grid.body.rows;
                                        var newIndex = _.indexOf(rowsView, this);

                                        if (previousIndex != null && previousIndex != newIndex) rowsView[previousIndex].$el.removeClass("selectedItem");

                                        that.model.set({
                                            index: newIndex,
                                        });

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

                        that.grid = grid;
                        that.$el.find('.last-heats-grid-container').append(grid.render().el);

                        that.isRendered = true;



                        that.trigger("render");


                    }, true, customPath);

                }, customPath, "assign_heats_torch_modal");

            },



            show: function () {
                if (!this.isRendered) {
                    this.render();
                }
                else {
                    this.$el.modal({
                        keyboard: true,
                        backdrop: 'both',
                    });
                }

                return this;
            },

            bindEvents: function () {
                this.listenToOnce(this, "render", this.view_render);
                this.listenTo(this.lastHeatsColl, 'fetch', this.lastHeats_ready);


            },

            lastHeats_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData: (that.lastHeatsColl.length > 0),
                                processing: false,
                                isLoading: false,
                            });
                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            close: function () {
                if (this.disposed == false) {
                    if (this.visible == true) {
                        this.hide();
                    }
                    else {
                        this.trigger('close');

                        this.remove();
                        this.unbind();

                        this.disposed = true;
                    }
                }
            },
            preRender: function () {
                app.models.subnavbar.set("dateControl", false);
            },
            reRender: function () {
            },

            acceptBtn_click: function (e) {
                try {
                    this.bus.trigger("modalAcceptBtn", this.model.get('currentProcessId'), this.model.get('selectedHeatId'));

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

            unassignBtn_click: function () {
                try {
                    //this.bus.trigger("modalUnassignBtn", this.model.get('currentProcessId'));

                    app.views.topMessages.showMessage('Method disabled. To unassign a Heat go to Caster Production screen ', { stay: 5000, });
                    this.close();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },

            form_submit: function (e) {
                try {
                    e.preventDefault();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            modal_hidden: function (e) {
                try {
                    this.visible = false;

                    if (!this.preventDispose)
                        this.close();
                    else
                        this.preventDispose = false;
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            modal_show: function (e) {
                try {
                    this.visible = true;
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            modal_shown: function (e) {
                try {
                    this.$el.find(".autofocus").focus();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            view_render: function () {
                try {
                    this.show();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },

        });

 


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