//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',
    'chart',
    'moment',
    'chartjs-date-fns-adapter',
  'modules/navigation-buttons/navigation-buttons',
  'backgrid/moment-cell',
    'js/autocomplete/backbone.autocomplete',
    'js/multiselect/virtual-select.min',
    'backgrid/grouped-columns',

],
    function (app, T, Backgrid, ChartJS, moment, ChartJsDateFnsAdapter, NavigationButton) {

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

    
    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {
            casterCodes: [{ label: '1', value: 1 }, { label: '2', value: 2 }],
            casterCode: 1,


            hasData_process: false,
            isLoading_process: false,


            hasData_strands: false,
            isLoading_strands: false,


            processId: null,
            heatId: null,
            direction: null,
            navigation: null,
            enterPress: false,
            logBookDescription: '',

            // Picker
            heatName: null,
            heatNames: [],


        },
        computeds: {
            strandPos1: {
                deps: ['casterCode'],
                get: function (caster) {
                    return caster === 1 ? 'Strand 1' : 'Strand 5';
                },
            },
            strandPos2: {
                deps: ['casterCode'],
                get: function (caster) {
                    return caster === 1 ? 'Strand 2' : 'Strand 6';
                },
            },
            strandPos3: {
                deps: ['casterCode'],
                get: function (caster) {
                    return caster === 1 ? 'Strand 3' : 'Strand 8';
                },
            },
            strandPos4: {
                deps: ['casterCode'],
                get: function (caster) {
                    return caster === 1 ? 'Strand 4' : 'Strand 9';
                },
            },
            hasData: {
                deps: ['hasData_process'],
                get: function (process) {
                    return process;
                },
            },
            isLoading: {
                deps: ['isLoading_process'],
                get: function (process) {
                    return process;
                },
            },
        },
        initialize: function () {
            this.process = new Screen.Models.Process();
            this.strand1 = new Screen.Models.Strand();
            this.strand2 = new Screen.Models.Strand();
            this.strand3 = new Screen.Models.Strand();
            this.strand4 = new Screen.Models.Strand();
            this.mainData = new Screen.Models.HeatReportMainData();
            this.secondaryData1 = new Screen.Models.SecondaryInfo1();
            this.secondaryData2 = new Screen.Models.SecondaryInfo2();
            this.products = new Screen.Collections.ProductsColl();

            this.probesColl = new Screen.Collections.ProbesColl();
        },

        fetch: function (params) {
            var that = this;
            var qp = new Core.Database.QueryParameters();
            qp.Add('@heatName', 'VARCHAR', that.get('heatName'));
            qp.Add('@timeZoneCode', 'CHAR(10)', app.models.user.get('timezoneCode'));

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

                            if (resp && resp.Table) {
                                var newColl = resp.Table[0];
                                that.set({
                                    casterCode: newColl.CasterCode,
                                });
                                that.process.setDataModel(resp.Table);
                                that.mainData.setDataModel(resp.Table);
                                that.secondaryData1.setDataModel(resp.Table);
                                that.secondaryData2.setDataModel(resp.Table);

                                if (resp.Table1) that.strand1.setDataModel(resp.Table1);
                                if (resp.Table2) that.strand2.setDataModel(resp.Table2);
                                if (resp.Table3) that.strand3.setDataModel(resp.Table3);
                                if (resp.Table4) that.strand4.setDataModel(resp.Table4);
                                if (resp.Table5) that.products.setDataColl(resp.Table5);
                                if (resp.Table6) that.probesColl.setDataColl(resp.Table6); else that.probesColl.setDataColl([]);
                                if (resp.Table7) that.trigger('fetch-nav-buttons', resp.Table7);                             
                                if (resp.Table8) that.trigger('chart-data-ready', resp.Table8, resp.Table9);
                            }
                            else {
                                if ((resp) && (resp.Message)) {
                                    app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                    console.error(resp.Message);
                                    that.set({
                                        hasData_process: false,
                                        isLoading_process: false,
                                        hasData_strands: false,
                                        isLoading_strands: false,

                                    });
                                }
                                else {
                                    app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                    console.error("Server response not valid.");
                                    that.set({
                                        hasData_process: false,
                                        isLoading_process: false,
                                        hasData_strands: false,
                                        isLoading_strands: false,

                                    });
                                }

                            }


                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Secured: true,
                },
                app.ConnectionStrings.app
            );

            return this;

        },

        fetchNavigateHeat: function (params) {
            var qp = new Core.Database.QueryParameters();
            var that = this;
            qp.Add('@heatName', 'VARCHAR(10)', that.get('heatName'));
            qp.Add('@direction', 'SMALLINT', params.direction);
            qp.Add('@Asset', 'CHAR(3)', 'CAS');

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.MES.GetNavigatedHeat',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if (resp && resp.Table && resp.Table[0] && resp.Table[0].HeatName && resp.Table[0].HeatName !== '') {
                               
                                that.set({
                                    heatName: resp.Table[0].HeatName,
                                    heatNames: [{
                                        value: resp.Table[0].HeatName,
                                        label: resp.Table[0].HeatName
                                    }],
                                });
                                that.trigger('heat-name-changed');
                            }
                            else {
                                if ((resp) && (resp.Message)) {
                                    app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                    console.error(resp.Message);
                                    that.set({
                                        hasData_process: false,
                                        isLoading_process: false,
                                    });
                                }
                                else {
                                    app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                    console.error("Server response not valid.");
                                    that.set({
                                        hasData_process: false,
                                        isLoading_process: false,
                                    });
                                }

                            }


                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );
        },
        fetchCatalogs: function () {
            var that = this;
            var qp = new Core.Database.QueryParameters();
            qp.Add('@HeatName', 'VARCHAR(10)', that.get('heatName'));
            qp.Add('@Asset', 'CHAR(3)', 'CAS');
            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.MES.GetAutocompleteHeats',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if (resp && resp.Table) {
                                that.set({
                                    heatNames: resp.Table,
                                    heatName: resp.Table[0] && resp.Table[0].value ? resp.Table[0].value : '',
                                    processId: resp.Table[0] && resp.Table[0].processId ? resp.Table[0].processId : null,
                                });
                                that.trigger('catalogs-fetched');
                            }
                            else {
                                if ((resp) && (resp.Message)) {
                                    app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                    console.error(resp.Message);
                                    that.set({
                                        hasData_process: false,
                                        isLoading_process: false,


                                    });
                                }
                                else {
                                    app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                    console.error("Server response not valid.");
                                    that.set({
                                        hasData_process: false,
                                        isLoading_process: false,
                                    });
                                }

                            }


                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );
        },





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

            qp.Add('@casterProcessId', 'INT', that.get('processId'));

            Core.Json.CallProcedure(
                app.DatabaseNames.LogBook + '.LB.InsertCasterLogEntry',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                that.trigger('LogBookReady');
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(new Error(resp.Message).stack);
                                else
                                    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;

        },

    });

    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-heat-report';
        } catch (Error) { }
    }

        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'caster-heat-report',
            id: 'caster-heat-report',
            title: 'CASTER Heat Report',
            isCacheable: false,
            events: function () {
                return {
                    'click #refreshBtn': this.refreshBtn_click,

                    'click #backNavBtn': this.heatNavigationBtn_click,
                    'click #forwardNavBtn': this.heatNavigationBtn_click,
                    'click #printBtn': this.printBtn_click,
                    //'click #logbookBtn': this.logbookBtn_click,
                };
            },
            bindings: 'data-bind',
            subviews: null,
            viewParams: null,

            process: null,

            phases: null,
            phaseChartView: null,
            autoCompleteCollection: null,
            autocompleteView: null,

            casterChart: null,
            casterChartPrint: null,
            NavigationButtonView: 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.NavigationButtonView = new NavigationButton.Views.Main();

                this.bindingSources = {
                    process: that.model.process,
                    strands: that.model.strands,
                    strand1: that.model.strand1,
                    strand2: that.model.strand2,
                    strand3: that.model.strand3,
                    strand4: that.model.strand4,
                    mainData: that.model.mainData,
                    secondaryData1: that.model.secondaryData1,
                    secondaryData2: that.model.secondaryData2,
                };

                this.bindEvents();

            },


            buildChart: function (names, all) {
                var ctx = document.getElementById('CasterChart').getContext('2d');
                var datasets = [];
                var scales = {};
                var position = 'left';
                var radius = 1;
                var type = 'line';
                var pointStyle = 'circle';
                var displayLegend = true;
                var displayLegendByType = true;
                if (this.chart) {
                    this.chart.destroy();
                };
                _.each(names, function (obj, i) {
                    if (obj.isEvent == true) {
                        radius = 5
                        type = 'bubble';
                        displayLegendByType = false;
                        pointStyle = 'triangle';
                    }
                    else {
                        radius = 1;
                        type = 'line';
                        displayLegendByType = true;
                        pointStyle = 'circle';
                    }
                    displayLegend = names[i].ShowYAxis != null ? names[i].ShowYAxis : displayLegendByType;
                    datasets.push({
                        label: obj.Name,
                        data: _.where(all, { Name: obj.Name }),
                        fill: false,
                        yAxisID: 'y' + i,
                        borderColor: obj.Color,
                        backgroundColor: obj.FillColor,
                        tension: 0.1,
                        borderWidth: 1,
                        radius: radius,
                        type: type,
                        pointStyle: pointStyle,

                    })
                    //position = i % 2 == 0 ? 'left' : 'right';
                    position = names[i].YAxisPosition ? names[i].YAxisPosition.replaceAll(/\s/g, '') : 'left';
                    if (i === 0) {
                        scales['x'] = {
                            type: 'time',
                            ticks: {
                                maxTicksLimit: 16,
                                autoSkip: true,
                                maxRotation: 0,
                                minRotation: 0
                            },
                        };
                        scales['y' + i] = {
                            type: 'linear',
                            position: position,
                            min: names[i].MinValue,
                            max: names[i].MaxValue,
                            display: true,
                            ticks: {
                                color: names[i].Color,
                                callback: function (value, index, values) {
                                    if (obj.UnitName) {
                                        return value + ' ' + obj.UnitName
                                    } else
                                        return value;
                                },

                            }
                        };

                    } else {
                        scales['y' + i] = {
                            type: 'linear',
                            position: position,
                            min: names[i].MinValue,
                            max: names[i].MaxValue,
                            display: displayLegend,
                            ticks: {
                                color: names[i].Color,
                                callback: function (value, index, values) {
                                    if (obj.UnitName) {
                                        return value + ' ' + obj.UnitName
                                    } else
                                        return value;
                                },
                            },
                            grid: {
                                drawOnChartArea: false, // only want the grid lines for one axis to show up
                            },

                        };
                    }
                });
                var pluginLabels = {
                    id: 'plugin_labels',
                    afterDatasetsDraw: (chart, args, options) => {
                        var { ctx } = chart;
                        ctx.save();
                        ctx.font = '12px sans-serif';
                        for (let x = 0; x < chart.config.data.datasets.length; x++) {
                            if (chart.config.data.datasets[x].type === 'bubble') {

                                for (let i = 0; i < chart.config.data.datasets[x].data.length; i++) {
                                    if (chart.config.data.datasets[x].data[i].isEvent === true) {
                                        let textWidth = ctx.measureText(chart.config.data.datasets[x].data[i].EventDescription).width;
                                        let text = chart.config.data.datasets[x].data[i].EventDescription;
                                        ctx.fillText(text, chart.getDatasetMeta(x).data[i].x - (textWidth / 2), chart.getDatasetMeta(x).data[i].y - 10);
                                    }
                                }
                            }

                        }
                        ctx.restore();
                    },

                }
                this.chart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        datasets: datasets
                    },
                    options: {
                        responsive: true,
                        spanGaps: true,
                        plugins: {
                            title: {
                                display: true,
                            },
                        },
                        scales: scales,

                    },
                    plugins: [pluginLabels],
                });



            },

            heatNameChanged: function () {
                const value = this.model.get('heatName');
                const options = this.model.get('heatNames');
                document.querySelector('#heat-picker-multi-select').setOptions(options);
                document.querySelector('#heat-picker-multi-select').setValue(value);
                this.UpdateURL();
                this.refresh();
            },
            heatNavigationBtn_click: function (e) {
                const { id } = e.target;
                const direction = id === 'backNavBtn' ? -1 : 1;
                this.model.fetchNavigateHeat({
                    direction
                });

            },

            renderMultipicker: function () {
                var that = this;
                var heatNamesPicker = new VirtualSelect.init({
                    ele: '#heat-picker-multi-select',
                    options: that.model.get('heatNames'),
                    multiple: false,
                    search: true,
                    placeholder: 'Select Heat',
                    hasOptionDescription: false,
                    showSelectedOptionsFirst: true,
                    hideClearButton: true,
                    onServerSearch: that.onSampleSelectServerSearch,
                });
                var heat = that.model.get('heatName');
                document.querySelector('#heat-picker-multi-select').setOptions(that.model.get('heatNames'));
                document.querySelector('#heat-picker-multi-select').setValue(heat);
                document.querySelector('#heat-picker-multi-select').addEventListener('change', function () {
                    $('.vscomp-search-clear').click();
                    if (this.value === that.model.get('heatName')) {
                        return 0;
                    }
                    else {
                        var newHeatName = this.value;
                        if (newHeatName && newHeatName != '') {
                            that.model.set({
                                heatName: newHeatName
                            });
                            that.refresh();
                            that.UpdateURL();
                        }
                    }
                });

            },

            onSampleSelectServerSearch: function (searchValue, virtualSelect) {
                var qp = new Core.Database.QueryParameters();
                qp.Add('@HeatName', 'VARCHAR(10)', searchValue);
                qp.Add('@SelectedHeatName', 'VARCHAR(10)', this.selectedValues[0]);
                qp.Add('@Asset', 'CHAR(3)', 'CAS');

                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.MES.GetAutocompleteHeats',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                virtualSelect.setServerOptions(resp.Table);

                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        },
                        Secured: true,
                        Async: false,
                    },
                    app.ConnectionStrings.app
                );
            },

            bindEvents: function () {
                this.listenTo(this.model.process, 'fetch', this.process_fetched);

                //this.listenTo(this.model.strand1, 'fetch', this.strands_fetched);
                //this.listenTo(this.model.strand2, 'fetch', this.strands_fetched);
                //this.listenTo(this.model.strand3, 'fetch', this.strands_fetched);
                this.listenTo(this.model.strand4, 'fetch', this.strands_fetched);

                this.listenTo(this.model, 'fetch-nav-buttons', this.fetchnavbuttons);
                this.listenTo(this.model, 'LogBookReady', this.redirectToLogBook);

                this.listenTo(this.model, 'heat-name-changed', this.heatNameChanged);
                this.listenTo(this.model, 'catalogs-fetched', this.catalogsFetched);

                this.listenTo(this.model, 'chart-data-ready', this.buildChart);

                this.listenTo(this.model.probesColl, 'fetch', this.probesColl_fetched);

            },

            printBtn_click: function () {
                window.print();
                return false;
            },

            logbookBtn_click: function () {
                this.model.createLogBookEntry();
            },

            redirectToLogBook: function () {
                var start = new moment().subtract(5, 'days').format('YYYYMMDD');
                var end = new moment().format('YYYYMMDD');

                var id = this.model.get('processId');
                var url = null;
                if (id)
                    url = '/!/casting-log-book/' + start + '/' + end  + '/-/-/-/-/-/' + id
                else
                    url = url = '!/casting-log-book/'
                Backbone.history.navigate(url, { trigger: true });
            },


            render: function (container, urlParams) {
                var that = this;
                var thatContainer = (this.options.container) ? this.options.container : container;
                this.options.container = thatContainer;

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

                                var grid = new Backgrid.Grid({
                                    className: 'grid-styles table',
                                    columns: [
                                        {
                                            name: 'ProductNumber',
                                            label: 'Product Number',
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.StringCell.extend({
                                                orderSeparator: '',
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'Length',
                                            editable: false,
                                            sortable: false,
                                            label: 'Length',
                                            cell: Backgrid.StringCell.extend({
                                                orderSeparator: '',
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'Weight',
                                            editable: false,
                                            sortable: false,
                                            label:'Weight',
                                            cell: Backgrid.StringCell.extend({
                                                orderSeparator: '',
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        
                                        {
                                            name: 'CutComplete',
                                            label: 'Cut Complete',
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell',
                                            }),
                                            headerCell: Backgrid.HeaderCell.extend({
                                                className: 'timestamp-date',
                                            }),
                                        }, 
                                        {
                                            name: 'isCrop',
                                            editable: false,
                                            sortable: false,
                                            label: 'is Crop',
                                            cell: Backgrid.StringCell.extend({
                                                orderSeparator: '',
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'isManual',
                                            editable: false,
                                            sortable: false,
                                            label: 'is Manual',
                                            cell: Backgrid.StringCell.extend({
                                                orderSeparator: '',
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'TaggingMachineCode',
                                            editable: false,
                                            sortable: false,
                                            label: 'Machine',
                                            cell: Backgrid.StringCell.extend({
                                                orderSeparator: '',
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'TaggingStatusCode',
                                            editable: false,
                                            sortable: false,
                                            label: 'Status',
                                            cell: Backgrid.StringCell.extend({
                                                orderSeparator: '',
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },

                                    ],

                                    header: Backgrid.Extension.GroupedHeader.extend({
                                        columnLayout:
                                            [
                                                {
                                                    name: 'Products', children:
                                                        [
                                                            { name: 'ProductNumber' }
                                                            , { name: 'Length' }
                                                            , { name: 'Weight' }
                                                            , { name: 'CutComplete' }
                                                            , { name: 'isCrop' }
                                                            , { name: 'isManual' }
                                                            , { name: 'isTail' }
                                                            , { name: 'TaggingMachineCode' }
                                                            , { name: 'TaggingStatusCode' }
                                                        ]
                                                },
                                            ],
                                        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.products,
                                });
                                that.$el.find('.process-products-grid-container').append(grid.render().el);



                                var probesColumns = [
                                    {
                                        name: 'datetime',
                                        label: 'Start',
                                        cell: Backgrid.StringCell.extend({
                                            className: function () {
                                                currentStart = new moment(this.model.get('datetime'), 'DD/MM/YYYY HH:mm:ss').format('YYYY-MM-DD HH:mm:ss');
                                                processEnd = new moment(that.model.process.get('endProcessLimit'), 'DD/MM/YYYY HH:mm:ss').format('YYYY-MM-DD HH:mm:ss');
                                                if (moment(currentStart).isAfter(processEnd, 'second')) return 'string-cell align-center-cell twenty-percent highlightRed';
                                                else return 'string-cell align-center-cell twenty-percent';
                                            }
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'temperature',
                                        label: app.translate(that, 'item_temperature_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell twenty-percent',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'oxygen',
                                        label: app.translate(that, 'item_oxygen_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell twenty-percent',
                                        }),
                                        editable: false,
                                    },
                                    {
                                        name: 'hydrogen',
                                        label: app.translate(that, 'item_hydrogen_col_label'),
                                        cell: Backgrid.StringCell.extend({
                                            className: 'string-cell align-center-cell twenty-percent',
                                        }),
                                        editable: false,
                                    },

                                ];
                                var probesGrid = new Backgrid.Grid({
                                    className: 'grid-styles table',

                                    header: Backgrid.Extension.GroupedHeader.extend({
                                        columnLayout:
                                            [
                                                {
                                                    name: 'Probes', children:
                                                        [
                                                            { name: 'datetime' }
                                                            , { name: 'temperature' }
                                                            , { name: 'oxygen' }
                                                            , { name: 'hydrogen' }
                                                        ]
                                                },
                                            ],
                                        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.probesColl,
                                    columns: probesColumns,
                                });
                                container.append(probesGrid.render().el);
                                that.$el.find('.probes-items-grid-container').append(probesGrid.render().el);

                             

                                that.applyBindings();

                               

                                //rendering Navigation Buttons
                                that.NavigationButtonView.render(that.$el.find(".navigation-buttons"), null);

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

                                //Autocomplete Heat Names
                                //that.autoCompleteCollection.setDataColl(that.model.get('heatNames'));

                                that.autocompleteView = new AutoCompleteView({
                                    input: $("#search"),
                                    minKeywordLength: 4,
                                    model: that.autoCompleteCollection,
                                }).render();


                                var fixedParams = _.extend({}, urlParams);
                                if (fixedParams && fixedParams.heatName && fixedParams.heatName.length === 7) {
                                    that.model.set(fixedParams);
                                } else {
                                    that.UpdateURL();
                                }
                                that.model.fetchCatalogs();

                                that.renderMultipicker();


                                that.refresh();

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

            refresh: function () {     
                this.model.set({
                    isLoading_process: true,
                    hasData_process: false,
                    hasData_strands: false,
                    isLoading_strands: true,
                });

                this.model.fetch();



            },

                             
            fetchnavbuttons: function (resp) {
                this.NavigationButtonView.setDataColl(resp);
            },
            probesColl_fetched: function () {
                try {
                    //var that = this;
                    //setTimeout(
                    //    function () {
                    //        that.model.set({
                    //            hasData_probes: (that.model.probesColl.length > 0),
                    //            isLoading_probes: false,
                    //        });

                    //    },
                    //    100
                    //);
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            process_fetched: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_process: that.model.process.get('id') ? true : false,
                                isLoading_process: false,
                                processId: that.model.process.get('id'),
                                heatName: that.model.process.get('heatName'),
                            });
                        },
                        100
                    );
                    this.UpdateURL();

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

             strands_fetched: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData_strands: ((that.model.strand1.length > 0) || (that.model.strand2.length > 0) || (that.model.strand3.length > 0) || (that.model.strand4.length > 0)),
                                isLoading_strands: false,
                            });

                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            UpdateURL: function () {
                try {
                    var params = this.model.toJSON();

                    app.router.navigate(
                        app.router.resolveURL(
                            app.router.currentModule,
                            _.extend(
                                {},
                                params,
                                {
                                    heatName: params.heatName,
                                }
                            ),
                            false
                        ),
                        { trigger: false, }
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },

        refreshBtn_click: function (e) {
            this.UpdateURL();
            this.refresh();

        },
        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 (urlParams) {
            try {
                this.refresh(viewParams);
            } catch (Error) { }
        },

    });


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

            //Header
            heatName: null,
            productionDate: null,
            start: null,
            end: null,
            shiftId: null,
            crewId: null,
            meltOrder: null,
            //Main data
            id: null,

            ladleArrival: null,
            ladleInCastPosition:null,
            ladleOpen:null,
            ladleClose: null,

            tundishNumber:null,
            sequence      :null,
            lastInSequence: null,

            initialWeight: null,
            finalWeight: null,


            minTundishTemperature: null,
            maxTundishTemperature: null,
            avgTundishTemperature: null,

            minTundishWeight: null,
            maxTundishWeight: null,
            avgTundishWeight: null,


            initGradeName: null,
            gradeName: null,
            ladleName: null,
            operatorName: null,

            waitTime: null,
            openTime: null,
            castTime: null,
        },
        computeds: {
            shiftName: {
                deps: ['shiftId'],
                get: function (shift) {
                    if (shift == 1) return 'D'
                    else if (shift == 2) return 'N'
                },
            },
            productionDateAndShift: {
                deps: ['shiftId','productionDate'],
                get: function (shift,date) {
                    if (shift == 1) return date + ' - ' + 'D'
                    else if (shift == 2) return date + ' - ' + 'N'
                },
            }
        },
        setDataModel: function (model) {
            if (model && model[0]) {
                var obj = model[0];
                this.set({
                    heatName: obj.HeatId ? obj.MESHeatName :(obj.HeatName ? obj.HeatName : null),
                    meltOrder: obj.MeltOrder ? obj.MeltOrder : null,
                    productionDate: obj.ProductionDate ? new moment(obj.ProductionDate).format('MM/DD/YYYY') : null,
                    shiftId: obj.ShiftId ? obj.ShiftId : null,
                    crewId: obj.CrewId ? obj.CrewId : null,
                    start: obj.StartLocal ? new moment(obj.StartLocal).format('HH:mm') : null,
                    end: obj.EndLocal ? new moment(obj.EndLocal).format('HH:mm') : null,
                    gradeName: obj.GradeName ? obj.GradeName : null,
                    id: obj.Id ? obj.Id : null,

                    ladleArrival: obj.LadleArrivalLocal ? new moment(obj.LadleArrivalLocal).format('HH:mm'): null,
                    ladleInCastPosition: obj.LadleInCastPositionLocal ? new moment(obj.LadleInCastPositionLocal).format('HH:mm') : null,
                    ladleOpen: obj.LadleOpenLocal ? new moment(obj.LadleOpenLocal).format('HH:mm') : null,
                    ladleClose: obj.LadleCloseLocal ? new moment(obj.LadleCloseLocal).format('HH:mm') : null,

                    tundishNumber: obj.TundishNumber ? obj.TundishNumber : null,
                    sequence        : obj.Sequence ? obj.Sequence : null ,
                    lastInSequence: obj.LastInSequence ? obj.LastInSequence : false,

                    initialWeight: obj.InitialWeight ? obj.InitialWeight : null,
                    finalWeight: obj.FinalWeight ? obj.FinalWeight : null,
                    ladleName: obj.LadleName ? obj.LadleName : null,



                    minTundishTemperature: obj.MinTundishTemperature ? obj.MinTundishTemperature.toFixed(0)     : null,
                    maxTundishTemperature: obj.MaxTundishTemperature ?      obj.MaxTundishTemperature.toFixed(0)     : null,
                    avgTundishTemperature: obj.AverageTundishTemperature ? obj.AverageTundishTemperature.toFixed(0) : null,
                    minTundishWeight:      obj.MinTundWeight    ?     obj.MinTundWeight          : null, 
                    maxTundishWeight:      obj.MaxTundWeight    ?     obj.MaxTundWeight          : null, 
                    avgTundishWeight:      obj.AvgTundWeight    ?     obj.AvgTundWeight      : null, 

                    waitTime: obj.WaitTime ? obj.WaitTime : null,
                    openTime: obj.OpenTime ? obj.OpenTime : null,
                    castTime: obj.CastTime ? obj.CastTime : null,
                }).trigger('fetch', this, obj);

            }
            else this.trigger('fetch', this, model);
        },
    });

    Screen.Models.SecondaryInfo1 = Backbone.Epoxy.Model.extend({
        defaults: {
            grade: null,
            ladle: null,
            tundish: null,
            last: null,
            minTundishTemperature: null,
            maxTundishTemperature: null,
            avgTundishTemperature: null,
            TundishTemps: null,
        },
        setDataModel: function (model) {
            if (model && model[0]) {
                var obj = model[0];

                var minTundishTemperature= obj.MinTundishTemperature ? obj.MinTundishTemperature.toFixed(0) : '-';
                var maxTundishTemperature= obj.MaxTundishTemperature ? obj.MaxTundishTemperature.toFixed(0) : '-';
                var avgTundishTemperature= obj.AverageTundishTemperature ? obj.AverageTundishTemperature.toFixed(0) : '-';
                this.set({
                    grade: obj.GradeName ? obj.GradeName : '-',
                    ladle: obj.LadleName ? obj.LadleName : '-',
                    tundish: obj.TundishId ? obj.TundishId : '-',
                    last: obj.LastInSequence === 'True' || obj.LastInSequence == 1 ? 'Yes' : 'No',
                    TundishTemps: `Min: ${minTundishTemperature} | Avg: ${avgTundishTemperature} | Max: ${maxTundishTemperature} `
                }).trigger('fetch', this, obj);

            }
            else this.trigger('fetch', this, model);
        },
    });
    Screen.Models.SecondaryInfo2 = Backbone.Epoxy.Model.extend({
        defaults: {
            waitTime: null,
            openTime: null,
            castTime: null,
            arrive: null,
            open: null,
            close: null,

        },
        setDataModel: function (model) {
            if (model && model[0]) {
                var obj = model[0];
                this.set({
                    waitTime: obj.WaitTime ? obj.WaitTime : '-',
                    openTime: obj.OpenTime ? obj.OpenTime : '-',
                    castTime: obj.CastTime ? obj.CastTime : '-',
                    arrive: obj.LadleArrivalLocal ? new moment(obj.LadleArrivalLocal).format('HH:mm') : '-',
                    open: obj.LadleOpenLocal ? new moment(obj.LadleOpenLocal).format('HH:mm') : '-',
                    close: obj.LadleCloseLocal ? new moment(obj.LadleCloseLocal).format('HH:mm') : '-',
                }).trigger('fetch', this, obj);

            }
            else this.trigger('fetch', this, model);
        },
    });

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

            heatName: null,
            meltOrder: null,
            date: null,
            shift: null,
            crew: null,
            start: null,
            end: null,
            freeOpen: null,
            headerInfo: null,
        },
        setDataModel: function (model) {
            if (model && model[0]) {
                var obj = model[0];

                var shift = obj.ShiftId === 1 ? 'Day' : 'Night'; 
                this.set({

                    heatName: obj.HeatName ? obj.HeatName : '-' ,
                    meltOrder: obj.MeltOrder ? obj.MeltOrder : '-',
                    date: obj.ProductionDate ? new moment(obj.ProductionDate).format('MM/DD/YYYY') : '-',
                    shift: obj.ShiftId === 1 ? 'D' : 'N',
                    crew: obj.CrewId ? obj.CrewId : '-',
                    start: obj.StartLocal ? new moment(obj.StartLocal).format('HH:mm') : null,
                    end: obj.EndLocal ? new moment(obj.EndLocal).format('HH:mm') : null,
                    freeOpen: obj.Rods ? 'N (' + obj.Rods + ')' : 'Y',
                    headerInfo: `Heat: ${obj.HeatName ? obj.HeatName : ''} | Caster ${obj.CasterCode === 1 ? '1' : '2'} | Date: ${obj.StartLocal ? new moment(obj.StartLocal).format('MM/DD/YYYY') : ''} | Shift: ${shift} | Crew: ${obj.CrewId ? obj.CrewId : obj.CrewId} | Start : ${obj.StartLocal ? new moment(obj.StartLocal).format('HH:mm') : ''} | End: ${obj.EndLocal ? new moment(obj.EndLocal).format('HH:mm') : ''} | Grade: ${obj.GradeName ? obj.GradeName : ''} | Ladle: ${obj.LadleName ? obj.LadleName : ''}`,

                }).trigger('fetch', this, obj);

            }
            else this.trigger('fetch', this, model);
        },
    });


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

            moldNumber: null,
            startLength: null,
            endLength: null,
            castedLength: null,
            sumProducts: null,
            strandLost: null,
        },
        setDataModel: function (model) {
            var obj = [];
            if (model && model[0]) obj = model[0];
            this.set({
                moldNumber: obj.MoldNumber ? obj.MoldNumber : null,
                startLength: obj.StartLength ? obj.StartLength.toFixed(0) : null,
                endLength: obj.EndLength ? obj.EndLength.toFixed(0) : null,
                castedLength: obj.CastedLength ? obj.CastedLength.toFixed(0) : null,
                sumProducts: obj.SumProducts ? obj.SumProducts : null,
                strandLost: (obj.StrandLost != null) ? (obj.StrandLost == false ? 'No' : 'Yes') : null,
            }).trigger('fetch', this, model);
          
        },
    });

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


        Screen.Models.ProbesColl = Backbone.Epoxy.Model.extend({
            defaults: {
                datetime: null,
                oxygen: null,
                temperature: null,
                hydrogen: null,
            },

            parse: function (obj) {
                var result = {
                    datetime: obj.Datetime ? new moment(obj.Datetime).format('MM/DD HH:mm') : null,
                    oxygen: obj.O ? obj.O : null,
                    temperature: obj.T ? obj.T : null,
                    hydrogen: obj.H ? obj.H : null,
                };
                return result;
            }

        });
        Screen.Collections.ProbesColl = Backbone.Collection.extend({
            model: Screen.Models.ProbesColl,
            comparator: 'datetime',
            setDataColl: function (data) {
                var newColl,
                    that = this;
                newColl = _.map(data, that.model.prototype.parse);
                that.set(newColl).trigger('fetch', that, data);
            },
        });  



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