//SCREEN-BOILERPLATE
//this boilerplate builds screens that are gonna be shown in the <div class='content'> tag of our main HTML.
//do not build app components with this boilerplate, only screens (reports)

define([
    // Application variable, always include it to have access to app methods.
    'app',

    //templates-loader: this loads templates async.
    'js/templates-loader',
    'backgrid',
    'moment',
    'chart',
    'chartjs-date-fns-adapter',

    'components/ag-grid/ag-grid-module',
    'backgrid/infinator',
    'backgrid/moment-cell',
    'backgrid/grouped-columns',

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

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

        Screen.Models.Main = Backbone.Epoxy.Model.extend({
            defaults: {
                start: new moment().subtract(2, 'days').format('YYYY-MM-DD'),
                end: new moment().format('YYYY-MM-DD'),
                heatName: null,
                hasData: false,
                isLoading: false,
                isPageLoading: false,
                grid: [],
                searchText: ''
            },
            computeds: {
                start$: {
                    deps: ['start'],
                    get: function (value) {
                        return value;
                    },
                    set: function (value) {
                        return { start: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                    },
                },
                end$: {
                    deps: ['end'],
                    get: function (value) {
                        return value;
                    },
                    set: function (value) {
                        return { end: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                    },
                },
            },
        });

        var CustomAgGridModule = AgGridModule.extend({
            initialize: function (options) {
                this.bus = options.bus;
                this.itemsColl = options.itemsColl;
                var that = this;
                
                // Store reference to modal for Actions column
                this.weatherTrendModal = options.weatherTrendModal;
                
                // Override onCellClicked in gridOptions
                if (!options.gridOptions) options.gridOptions = {};
                options.gridOptions.onCellClicked = function(params) {
                    // Handle click on HeatNumber column
                    if (params.column && params.column.colDef.field === 'HeatNumber' && params.value) {
                        var heatNumber = params.value;
                        Backbone.history.navigate('!/caster-heat-report/' + heatNumber, { trigger: true });
                        return;
                    }
                    
                    // Call parent onCellClicked for other columns
                    AgGridModule.prototype.onCellClicked.call(that, params);
                };
                
                this.columnDefs = [
                    { 
                        field: 'HeatNumber', 
                        headerName: 'Heat Number', 
                        flex: 1, 
                        showFilter: true,
                        cellRenderer: this.heatNumberCellRenderer.bind(this),
                        cellStyle: { textAlign: 'center' },
                        headerClass: 'ag-header-cell-center'
                    },
                    { 
                        field: 'LadleOpenTimeStamp', 
                        headerName: 'Ladle Open Time', 
                        flex: 1, 
                        minWidth: 150, 
                        showFilter: true, 
                        fieldType: 'Datetime', 
                        format: 'MM/DD HH:mm',
                        cellStyle: { textAlign: 'center' },
                        headerClass: 'ag-header-cell-center'
                    },
                    { 
                        field: 'AbsoluteHumidity', 
                        headerName: 'Absolute Humidity (g/m³)', 
                        flex: 1, 
                        showFilter: false, 
                        valueFormatter: this.decimalFormatter.bind(this, 4),
                        cellStyle: { textAlign: 'right' },
                        headerClass: 'ag-header-cell-center'
                    },
                    { 
                        field: 'OneHourPreviousAverageAbsoluteHumidity', 
                        headerName: '1H Avg (g/m³)', 
                        flex: 1, 
                        showFilter: false, 
                        valueFormatter: this.decimalFormatter.bind(this, 4),
                        cellStyle: { textAlign: 'right' },
                        headerClass: 'ag-header-cell-center'
                    },
                    { 
                        field: 'TwoHourPreviousAverageAbsoluteHumidity', 
                        headerName: '2H Avg (g/m³)', 
                        flex: 1, 
                        showFilter: false, 
                        valueFormatter: this.decimalFormatter.bind(this, 4),
                        cellStyle: { textAlign: 'right' },
                        headerClass: 'ag-header-cell-center'
                    },
                    { 
                        field: 'ThreeHourPreviousAverageAbsoluteHumidity', 
                        headerName: '3H Avg (g/m³)', 
                        flex: 1, 
                        showFilter: false, 
                        valueFormatter: this.decimalFormatter.bind(this, 4),
                        cellStyle: { textAlign: 'right' },
                        headerClass: 'ag-header-cell-center'
                    },
                    { 
                        field: 'FourHourPreviousAverageAbsoluteHumidity', 
                        headerName: '4H Avg (g/m³)', 
                        flex: 1, 
                        showFilter: false, 
                        valueFormatter: this.decimalFormatter.bind(this, 4),
                        cellStyle: { textAlign: 'right' },
                        headerClass: 'ag-header-cell-center'
                    },
                    { 
                        field: 'FiveHourPreviousAverageAbsoluteHumidity', 
                        headerName: '5H Avg (g/m³)', 
                        flex: 1, 
                        showFilter: false, 
                        valueFormatter: this.decimalFormatter.bind(this, 4),
                        cellStyle: { textAlign: 'right' },
                        headerClass: 'ag-header-cell-center'
                    },
                    { 
                        field: 'SixHourPreviousAverageAbsoluteHumidity', 
                        headerName: '6H Avg (g/m³)', 
                        flex: 1, 
                        showFilter: false, 
                        valueFormatter: this.decimalFormatter.bind(this, 4),
                        cellStyle: { textAlign: 'right' },
                        headerClass: 'ag-header-cell-center'
                    },
                    { 
                        field: 'OpenTemperature', 
                        headerName: 'Temperature (°C)', 
                        flex: 1, 
                        showFilter: false, 
                        valueFormatter: this.decimalFormatter.bind(this, 2),
                        cellStyle: { textAlign: 'right' },
                        headerClass: 'ag-header-cell-center'
                    },
                    { 
                        field: 'RelativeHumidityAtOpenOfHeat', 
                        headerName: 'Relative Humidity (%)', 
                        flex: 1, 
                        showFilter: false, 
                        valueFormatter: this.decimalFormatter.bind(this, 2),
                        cellStyle: { textAlign: 'right' },
                        headerClass: 'ag-header-cell-center'
                    },
                    { 
                        field: 'Actions', 
                        headerName: 'Actions', 
                        flex: 0.5, 
                        minWidth: 80,
                        showFilter: false,
                        suppressCellSelection: true,
                        cellStyle: { textAlign: 'center' },
                        headerClass: 'ag-header-cell-center',
                        cellRenderer: this.actionsCellRenderer.bind(this)
                    }
                ];

                // Pass the columns to the options
                options.columnDefs = this.columnDefs;

                // Initialize ag-Grid
                AgGridModule.prototype.initialize.call(this, options);
            },
            decimalFormatter: function (decimals, params) {
                if (params.value == null || params.value === '') return '';
                return parseFloat(params.value).toFixed(decimals);
            },
            heatNumberCellRenderer: function (params) {
                if (!params.value) return '';
                return '<span class="heat-link" style="color: #007bff; cursor: pointer; text-decoration: underline;">' + params.value + '</span>';
            },
            actionsCellRenderer: function (params) {
                // Create the trend graph button
                const trendBtn = document.createElement('button');
                trendBtn.className = 'btn btn-sm';
                trendBtn.setAttribute('title', 'View Weather Trends');
                trendBtn.style.display = 'inline-block';
                trendBtn.style.minWidth = '30px';
                trendBtn.style.minHeight = '24px';
                trendBtn.style.padding = '2px 8px';
                trendBtn.style.border = 'none';
                trendBtn.style.background = 'transparent';
                trendBtn.style.cursor = 'pointer';
                trendBtn.innerHTML = `
                    <i class="fa fa-line-chart" style="color: #007bff; font-size: 18px;" aria-hidden="true"></i>
                `;

                const rowData = params.data;
                var that = this; // Store reference to 'this' for use in event listener

                // Add click event listener
                trendBtn.addEventListener('click', function (e) {
                    e.stopPropagation();
                    if (that.weatherTrendModal && rowData) {
                        that.weatherTrendModal.show(rowData);
                    }
                });

                // Create container
                const container = document.createElement('div');
                container.className = 'flex justify-center';
                container.style.display = 'inline-block';
                container.style.minWidth = '40px';
                container.style.minHeight = '24px';
                container.appendChild(trendBtn);

                return container;
            }
        });

        Screen.Models.WeatherTrendModal = Backbone.Epoxy.Model.extend({
            defaults: {
                HeatNumber: null,
                showAbsoluteHumidity: true,
                showTemperature: true,
                showRelativeHumidity: true
            }
        });

        Screen.Views.WeatherTrendModal = Backbone.Epoxy.View.extend({
            template: "weather-tracking-summary",
            id: "weather-trend-modal",
            className: "modal hide fade",
            bindings: "data-bind",
            isRendered: false,
            disposed: false,
            visible: false,
            chart: null,
            events: function () {
                return {
                    "click .close": "closeBtn_click",
                    "click .btn-close": "closeBtn_click",
                    // Checkbox functionality commented out - all datasets are always visible
                    // "change .variable-checkbox": "checkbox_changed",
                    "show.bs.modal": "modal_show",
                    "shown.bs.modal": "modal_shown",
                    "hidden.bs.modal": "modal_hidden"
                };
            },
            initialize: function (options) {
                _.extend(this, options);
                if (!this.model) {
                    this.model = new Screen.Models.WeatherTrendModal();
                }
                this.bus = options.bus || _.extend({}, Backbone.Events);
                this.isRendered = false;
                this.disposed = false;
                this.visible = false;
                this.chart = null;
                this.bindEvents();
                _.bindAll(this);
            },
            bindEvents: function () {
                this.listenToOnce(this, "render", this.view_render);
            },
            render: function (container) {
                if (container)
                    this.container = container;

                var that = this;
                var customPath = '/app/pages/mes/weather-tracking-summary/';
                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();
                        that.isRendered = true;
                        that.trigger("render");
                    }, true, customPath);
                }, customPath, "weather-trend-modal");
            },
            show: function (rowData) {
                if (!this.isRendered) {
                    this.render();
                    var that = this;
                    setTimeout(function () {
                        that.show(rowData);
                    }, 100);
                    return;
                }

                // Set model with row data
                if (rowData) {
                    this.model.set({
                        HeatNumber: rowData.HeatNumber || rowData.HeatName,
                        showAbsoluteHumidity: true,
                        showTemperature: true,
                        showRelativeHumidity: true
                    });
                    this.currentRowData = rowData;
                }

                // Transform data and render chart
                if (rowData) {
                    var that = this;
                    var timeSeriesData = this.transformRowDataToTimeSeries(rowData);
                    if (timeSeriesData) {
                        setTimeout(function () {
                            that.renderChart(timeSeriesData);
                        }, 300);
                    }
                }

                this.$el.modal({
                    keyboard: true,
                    backdrop: 'both'
                });

                return this;
            },
            hide: function () {
                this.$el.modal('hide');
            },
            close: function () {
                if (this.disposed == false) {
                    if (this.visible == true) {
                        this.hide();
                    }
                    else {
                        this.trigger('close');
                        if (this.chart) {
                            this.chart.destroy();
                            this.chart = null;
                        }
                        try {
                            // Only remove if $el exists and is in the DOM
                            if (this.$el && this.$el.length > 0 && this.$el[0] && this.$el[0].parentNode) {
                                // Call Backbone.View.remove() which handles cleanup
                                Backbone.View.prototype.remove.call(this);
                            }
                        } catch (e) {
                            // Element may already be removed or $el is undefined
                            // Silently ignore - element cleanup is not critical
                        }
                        this.unbind();
                        this.disposed = true;
                    }
                }
            },
            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); }
            },
            modal_hidden: function (e) {
                try {
                    this.visible = false;
                    if (this.chart) {
                        this.chart.destroy();
                        this.chart = null;
                    }
                    if (!this.preventDispose)
                        this.close();
                    else
                        this.preventDispose = false;
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            closeBtn_click: function (e) {
                e.preventDefault();
                this.trigger('cancel');
                this.hide();
            },
            view_render: function () {
                try {
                    // Modal is rendered and ready, but don't auto-show
                    // It will be shown when show() is called explicitly
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            transformRowDataToTimeSeries: function (rowData) {
                // Try to parse the timestamp - it might be a string or Date object
                var ladleOpenTime;
                if (rowData.LadleOpenTimeStamp instanceof Date) {
                    ladleOpenTime = moment(rowData.LadleOpenTimeStamp);
                } else if (typeof rowData.LadleOpenTimeStamp === 'string') {
                    // The grid displays it as 'MM/DD HH:mm' format (without year)
                    // Try parsing with current year first
                    var currentYear = moment().year();
                    var timestampStr = rowData.LadleOpenTimeStamp.trim();
                    
                    // If format is MM/DD HH:mm, add current year
                    if (/^\d{1,2}\/\d{1,2}\s+\d{1,2}:\d{2}$/.test(timestampStr)) {
                        ladleOpenTime = moment(timestampStr + ' ' + currentYear, 'MM/DD HH:mm YYYY');
                    } else {
                        // Try other common formats
                        ladleOpenTime = moment(rowData.LadleOpenTimeStamp, ['YYYY-MM-DD HH:mm:ss', 'MM/DD/YYYY HH:mm', 'YYYY-MM-DDTHH:mm:ss', moment.ISO_8601]);
                    }
                } else {
                    ladleOpenTime = moment(rowData.LadleOpenTimeStamp);
                }
                
                if (!ladleOpenTime.isValid()) {
                    console.error('Invalid LadleOpenTimeStamp:', rowData.LadleOpenTimeStamp);
                    return null;
                }

                // Create time labels and data points for Absolute Humidity (7 points)
                var absoluteHumidityData = [];
                var timeLabels = [];
                
                // T-6H to T-0H
                for (var i = 6; i >= 0; i--) {
                    var timePoint = moment(ladleOpenTime).subtract(i, 'hours');
                    timeLabels.push(timePoint.toDate());
                    
                    var value = null;
                    if (i === 6) value = rowData.SixHourPreviousAverageAbsoluteHumidity;
                    else if (i === 5) value = rowData.FiveHourPreviousAverageAbsoluteHumidity;
                    else if (i === 4) value = rowData.FourHourPreviousAverageAbsoluteHumidity;
                    else if (i === 3) value = rowData.ThreeHourPreviousAverageAbsoluteHumidity;
                    else if (i === 2) value = rowData.TwoHourPreviousAverageAbsoluteHumidity;
                    else if (i === 1) value = rowData.OneHourPreviousAverageAbsoluteHumidity;
                    else if (i === 0) value = rowData.AbsoluteHumidity;
                    
                    absoluteHumidityData.push(value);
                }

                // Temperature and Relative Humidity (single point at T-0H)
                var temperatureData = [];
                var relativeHumidityData = [];
                
                for (var j = 6; j >= 0; j--) {
                    if (j === 0) {
                        temperatureData.push(rowData.OpenTemperature);
                        relativeHumidityData.push(rowData.RelativeHumidityAtOpenOfHeat);
                    } else {
                        temperatureData.push(null);
                        relativeHumidityData.push(null);
                    }
                }

                return {
                    labels: timeLabels,
                    absoluteHumidity: absoluteHumidityData,
                    temperature: temperatureData,
                    relativeHumidity: relativeHumidityData
                };
            },
            renderChart: function (timeSeriesData) {
                if (!timeSeriesData || !timeSeriesData.labels) {
                    console.error('Invalid time series data');
                    return;
                }

                var canvas = document.getElementById('weatherTrendChart');
                if (!canvas) {
                    console.error('Canvas element not found');
                    return;
                }

                var ctx = canvas.getContext('2d');

                // Destroy existing chart if it exists
                if (this.chart) {
                    this.chart.destroy();
                    this.chart = null;
                }

                var that = this;
                // Checkbox functionality commented out - all datasets are always visible
                // var showAbsHum = this.model.get('showAbsoluteHumidity');
                // var showTemp = this.model.get('showTemperature');
                // var showRelHum = this.model.get('showRelativeHumidity');

                this.chart = new ChartJS(ctx, {
                    type: 'line',
                    data: {
                        labels: timeSeriesData.labels,
                        datasets: [
                            {
                                label: 'Absolute Humidity (g/m³)',
                                data: timeSeriesData.absoluteHumidity,
                                borderColor: 'rgb(75, 192, 192)',
                                backgroundColor: 'rgba(75, 192, 192, 0.2)',
                                yAxisID: 'y',
                                hidden: false, // Always visible - checkbox functionality commented out
                                tension: 0.1
                            },
                            {
                                label: 'Temperature (°C)',
                                data: timeSeriesData.temperature,
                                borderColor: 'rgb(255, 99, 132)',
                                backgroundColor: 'rgba(255, 99, 132, 0.2)',
                                yAxisID: 'y1',
                                hidden: false, // Always visible - checkbox functionality commented out
                                pointRadius: 5,
                                pointHoverRadius: 7
                            },
                            {
                                label: 'Relative Humidity (%)',
                                data: timeSeriesData.relativeHumidity,
                                borderColor: 'rgb(54, 162, 235)',
                                backgroundColor: 'rgba(54, 162, 235, 0.2)',
                                yAxisID: 'y1',
                                hidden: false, // Always visible - checkbox functionality commented out
                                pointRadius: 5,
                                pointHoverRadius: 7
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        interaction: { mode: 'index', intersect: false },
                        plugins: {
                            legend: { display: true, position: 'top' },
                            tooltip: { 
                                mode: 'index', 
                                intersect: false,
                                callbacks: {
                                    title: function(context) {
                                        var label = context[0].label;
                                        // label is already a Date object from the time scale
                                        if (label instanceof Date) {
                                            return moment(label).format('MM/DD HH:mm');
                                        }
                                        // Fallback: try to parse as string or use as-is
                                        return moment(label, moment.ISO_8601, true).isValid() 
                                            ? moment(label).format('MM/DD HH:mm')
                                            : String(label);
                                    }
                                }
                            }
                        },
                        scales: {
                            x: {
                                type: 'time',
                                time: {
                                    unit: 'hour',
                                    displayFormats: {
                                        hour: 'HH:mm'
                                    },
                                    tooltipFormat: 'MM/dd HH:mm'
                                },
                                title: { display: true, text: 'Time' },
                                adapters: {
                                    date: ChartJsDateFnsAdapter
                                },
                                ticks: {
                                    source: 'data'
                                }
                            },
                            y: {
                                type: 'linear',
                                position: 'left',
                                title: { display: true, text: 'Absolute Humidity (g/m³)' }
                            },
                            y1: {
                                type: 'linear',
                                position: 'right',
                                title: { display: true, text: 'Temperature (°C) / Relative Humidity (%)' },
                                grid: { drawOnChartArea: false }
                            }
                        }
                    }
                });
            },
            // Checkbox functionality commented out - all datasets are always visible
            // To re-enable: uncomment this method and the event handler in events()
            /*
            checkbox_changed: function (e) {
                var checkbox = $(e.currentTarget);
                var variable = checkbox.data('variable');
                var checked = checkbox.is(':checked');

                if (!this.chart) return;

                // Update model
                if (variable === 'absoluteHumidity') {
                    this.model.set('showAbsoluteHumidity', checked);
                    this.chart.getDatasetMeta(0).hidden = !checked;
                } else if (variable === 'temperature') {
                    this.model.set('showTemperature', checked);
                    this.chart.getDatasetMeta(1).hidden = !checked;
                } else if (variable === 'relativeHumidity') {
                    this.model.set('showRelativeHumidity', checked);
                    this.chart.getDatasetMeta(2).hidden = !checked;
                }

                this.chart.update();
            }
            */
        });

        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'weather-tracking-summary',
            id: 'weather-tracking-summary',
            title: 'Weather Tracking Summary',
            events: function () {
                return {
                    'click #refreshBtn': this.refreshBtn_click,
                    'click #calendarStartBtn': this.calendarStartBtn_click,
                    'click #calendarEndBtn': this.calendarEndBtn_click,
                };
            },
            bindings: 'data-bind',
            bindingSources: null,
            grids: null,
            itemsColl: null,
            subviews: null,
            viewParams: null,

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

                var that = this;

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

                this.itemsColl = new Screen.Collections.Items();

                this.bindingSources = {};

                this.subviews = {};
                
                // Initialize bus before creating modal
                this.bus = _.extend({}, Backbone.Events);
                
                // Initialize Weather Trend Modal (before ag-Grid so it can be passed as reference)
                this.subviews.weatherTrendModal = new Screen.Views.WeatherTrendModal({
                    bus: this.bus
                });

                // Init AgGridModule:
                this.agGridModule = new CustomAgGridModule({
                    itemsColl: this.itemsColl,
                    bus: this.bus,
                    rowData: [],
                    onChange: this.handleGridChange.bind(this),
                    onRemove: this.handleGridRemove.bind(this),
                    fileName: 'weather-tracking-summary-report',
                    screenTitle: 'Weather Tracking Summary Report',
                    isPageLoading: that.model.get('isPageLoading'),
                    weatherTrendModal: this.subviews.weatherTrendModal
                });
                this.grids = {};
                
                this.autoRefresh = {
                    enabled: null
                    , toid: null
                    , every: 5 * 1000
                };

                this.bindEvents();
            },
            handleGridChange: function (event) {
                // This function will be called when a cell value changes
            },
            handleGridRemove: function () {
                // This function will be called when the grid is being removed/destroyed
            },
            calendarStartBtn_click: function () {
                $('#dateStartTbx').datepicker('show');
            },
            calendarEndBtn_click: function () {
                $('#dateEndTbx').datepicker('show');
            },
            bindEvents: function () {
                this.listenTo(this.itemsColl, 'backgrid:rowclick', this.processes_backgrid_rowclick)
                    .listenTo(this.itemsColl, 'fetch', this.processes_ready)
                    .listenTo(this.model, 'triggerFetch', this.refreshBtn_click);
            },
            removeHighlightRow: function () {
                var previousIndex = this.model.get('index');
                var rowsView = this.model.get('grid').body.rows;

                if (rowsView && rowsView[previousIndex] && rowsView[previousIndex].$el)
                    rowsView[previousIndex].$el.removeClass("onRightClickSelectedRow");
            },
            _refresh: function (opt) {
                this.itemsColl.reset();
                this.model.set({
                    hasData: false,
                });

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

                this.refreshProcesses(opt);

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

                    this.autoRefresh.toid = setTimeout(
                        function () { that._refresh(); },
                        this.autoRefresh.every
                    );
                }
            },
            refresh: function (viewParams) {
                var fixedParams = _.extend({}, Screen.Models.Main.prototype.defaults, viewParams);

                if (viewParams.start)
                    fixedParams.start = new moment(viewParams.start, 'YYYYMMDD').format('YYYY-MM-DD');
                if (viewParams.end)
                    fixedParams.end = new moment(viewParams.end, 'YYYYMMDD').format('YYYY-MM-DD');
                if (viewParams.heatName)
                    fixedParams.heatName = viewParams.heatName;

                this.model.set(fixedParams);

                this._refresh({
                    reset: true,
                    params: _.extend(
                        {},
                        fixedParams,
                        {}
                    ),
                });
            },
            render: function (container, viewParams) {
                var that = this;

                this.viewParams = viewParams;

                // Initialize the loading state
                that.model.set({ isPageLoading: true });

                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/pages/mes/weather-tracking-summary/';

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

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

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

                                that.applyBindings();

                                //start: the view was already loaded an is on a div element, but not appended to the main container
                                //here you can perform anything you want DOM related, by getting the dom element via that.$el.find('#id')
                                //or this.$('#id')

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

                                // Render the Weather Trend Modal and append to body
                                that.subviews.weatherTrendModal.render();
                                $('body').append(that.subviews.weatherTrendModal.$el);

                                // Render the AgGridModule and append it to the container
                                that.agGridModule.render();
                                that.$el.find('.processes-grid-container').append(that.agGridModule.$el);

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

                                //Set model with view params here to prevent changes on the model when the view bindings are applied.
                                var fixedParams = _.extend({}, viewParams);

                                if (fixedParams.start)
                                    fixedParams.start = new moment(fixedParams.start, 'YYYYMMDD').format('YYYY-MM-DD');
                                if (fixedParams.end)
                                    fixedParams.end = new moment(fixedParams.end, 'YYYYMMDD').format('YYYY-MM-DD');
                                if (fixedParams.heatName)
                                    fixedParams.heatName = fixedParams.heatName;

                                that.model.set(fixedParams);

                                //Call first refresh.
                                var params = that.model.toJSON();

                                that._refresh({
                                    reset: true,
                                    params: _.extend(
                                        {},
                                        params,
                                        {}
                                    ),
                                });

                                // Set loading state to false when everything is ready
                                that.model.set({ isPageLoading: false });
                            },
                            true,
                            customPath
                        );
                    },
                    customPath
                );
            },
            processes_ready: function () {
                try {
                    var that = this;
                    const collectionData = that.itemsColl;
                    setTimeout(
                        function () {
                            that.agGridModule.setRowDataAsCollection(collectionData);
                            that.agGridModule.hideOverlay();  // Hide loading overlay
                            that.model.set({
                                hasData: (that.itemsColl.length > 0),
                                isLoading: false,
                            });
                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },

            search_keypress: function (e) {
                if (e.keyCode === 13) {
                    $('#search').blur();
                    this.refreshBtn_click();
                }
            },
            refreshProcesses: function (options) {
                var that = this,
                    attrs = this.model.toJSON(),
                    opt = _.extend({}, options, { params: {}, });

                if ((opt.refresh == true) || (opt.reset == true)) {
                    this.model.set('isLoading', true);
                    that.agGridModule.showLoadingOverlay();  // Show loading overlay
                }

                this.itemsColl.fetch({
                    start: attrs.start,
                    end: attrs.end,
                    heatName: (attrs.heatName && attrs.heatName != '') ? attrs.heatName : null,
                    searchText: attrs.searchText,
                    refresh: true,
                });
            },
            processes_backgrid_rowclick: function (model) {
                try {
                    // Can add navigation or detail view here if needed
                }
                catch (Error) { console.error(Error.stack); }
            },
            refreshBtn_click: function (e) {
                try {
                    var params = this.model.toJSON();
                    var urlParams = {
                        start: new moment(params.start, 'YYYY-MM-DD').format('YYYYMMDD'),
                        end: new moment(params.end, 'YYYY-MM-DD').format('YYYYMMDD'),
                    };
                    if (params.heatName) {
                        urlParams.heatName = params.heatName;
                    }
                    app.router.navigate(
                        app.router.resolveURL(
                            app.router.currentModule,
                            _.extend({}, urlParams),
                            false
                        ),
                        { trigger: false, replace: true }
                    );

                    this._refresh({
                        reset: true
                    });

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

            //Common functions
            append: function (container, el) {
                el = (el != null && el != undefined) ? el : this.$el;

                if (this.options.state == app.view_states.loading
                    || this.options.state == app.view_states.shown) {
                    //appending view to the main container and set state to shown

                    this.options.state = app.view_states.shown;
                    container.append(el);

                    this.options.onappend(this);
                }

                if (this.options.state == app.view_states.hidden) {
                    //append and remain hidden
                    container.append(el);
                }

                if (this.options.state == app.view_states.closed) {
                    //return without appending.
                    return;
                }
            },
            bindViewScopedEvents: function () {
                var that = this;
            },
            unbindViewScopedEvents: function () {

            },
            close: function () {
                this.options.state = app.view_states.closed;

                this.closeSubviews();
                this.remove();
                this.unbindViewScopedEvents();
                this.unbind();
            },
            closeSubviews: function () {
                _.each(this.subviews, function (sview) {
                    sview.close();
                });
            },
            show: function () {
                this.options.state = app.view_states.shown;

                this.showSubviews();
                this.bindEvents();
                this.$el.show();
            },
            showSubviews: function () {
                _.each(this.subviews, function (sview) {
                    sview.show();
                });
            },
            hide: function () {
                this.options.state = app.view_states.hidden;

                this.hideSubviews();

                this.$el.hide();
                this.unbind();
                this.stopListening();
            },
            hideSubviews: function () {
                _.each(this.subviews, function (sview) {
                    sview.hide();
                });
            },
            preRender: function () {
                app.models.subnavbar.set("subnavbar", false);
            },
            reRender: function (viewParams) {
                try {
                    this.refresh(viewParams);
                } catch (Error) { }
            },
        });

        Screen.Collections.Items = Backbone.Collection.extend({
            isFetching: false,
            currentPage: 1,
            pageSize: 100,

            fixedParameters: [],

            fetch: function (params) {
                var that = this,
                    qp = new Core.Database.QueryParameters(),
                    options = params ? _.clone(params) : {};
                if (options.refresh) {
                    this.resetPagination(true);
                    this.fixedParameters = [
                        { Name: '@Start', Type: 'DATETIME', Value: params.start, },
                        { Name: '@End', Type: 'DATETIME', Value: params.end, },
                        { Name: '@HeatName', Type: 'VARCHAR', Value: params.heatName, },
                    ];
                }
                this.isFetching = true;

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

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

                                if ((resp) && (resp.Table)) {
                                    newColl = resp.Table;
                                    var method = (options.refresh) ? 'set' : 'add';
                                    that[method](newColl);
                                    that.trigger('fetch', that, newColl);

                                    if (newColl.length == 0 && method == 'add')
                                        that.currentPage--;

                                    that.isFetching = false;
                                }
                                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);
                            that.isFetching = false;
                        },
                        Secured: true,
                        Async: true,
                    },
                    app.ConnectionStrings.app
                );
                return this;
            },
            getNextPage: function (options) {
                if (!this.isFetching) {
                    this.currentPage++;
                    options = (_.isObject(options)) ? options : {};
                    this.fetch(options);
                }
            },
            resetPagination: function (force) {
                if (!this.isFetching || force == true) {
                    this.currentPage = 1;
                } else {
                    _.delay(this.resetPagination, 100);
                }
            },
        });

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

