
define([   
    'app',
    'js/templates-loader',
    'moment',
    'components/ag-grid/ag-grid-module',
    'components/modal-covers/modal-assign-cover',
],
    function (app, T, moment, AgGridModule, AssignCoverModal) {

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

        Screen.Models.Main = Backbone.Epoxy.Model.extend({
            defaults: {
                screenTitle: 'Covers Temperatures',
                start: new moment().subtract(2, 'days').format('YYYY-MM-DD'),
                end: new moment().format('YYYY-MM-DD'),               
                isLoading: false,
                isLoadingRt: false,
                remainingSeconds: 1,
                refreshIn: 'Refresh IN 1',
                renderCompleted: false,
            },
            computeds: {
                start$: {
                    deps: ['start'],
                    get: function (value) {
                        return value;
                    },
                    set: function (value) {
                        return { start: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                    },
                },
                end$: {
                    deps: ['end'],
                    get: function (value) {
                        return value;
                    },
                    set: function (value) {
                        return { end: (value) ? new moment(value, app.translate(app, 'MM/DD/YYYY')).format('YYYY-MM-DD') : value, };
                    },
                },
            },
            
           
        });

        var CustomAgGridModule = AgGridModule.extend({
            initialize: function(options) {
                this.columnDefs = options.columnDefs.map(colDef => {
                    if (colDef.children && colDef.children.length) {
                        // If there are children, map through the children and apply the renderer to 'ST' fields
                        colDef.children = colDef.children.map(childColDef => {
                            if (childColDef.field && childColDef.field.endsWith('ST')) {
                                return {
                                    ...childColDef,
                                    cellRenderer: this.statusCellRenderer
                                };
                            }
                            return childColDef;
                        });
                    }
                    return colDef;
                });
                AgGridModule.prototype.initialize.call(this, options);
                
            },
        
        
            statusCellRenderer: function(params) {
                const value = params.value;
                let statusClass = '';
                let statusText = '';
        
                if (value === 'L' || value === 'Lost') {
                    statusClass = 'bg-red-500 text-white';
                    statusText = 'L';
                } else if (value === 'G' || value === 'Good') {
                    statusClass = 'bg-green-500 text-white';
                    statusText = 'G';
                }
        
                return `<div class="flex justify-center mt-2">
                <span class="px-2 py-1 rounded-full text-xs font-semibold ${statusClass} w-16 text-center">
                  ${statusText}
                </span>
              </div>`;
            }
        });


        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'covers-temperatures',
            id: 'covers-temperatures',
            title: 'Covers Temperatures',
            events: function () {
                return {
                    'click #refreshBtnRt': this.refreshBtnRt_click,
                    'click #calendarStartBtn': function() { $('#dateStartTbx').datepicker('show'); },
                    'click #calendarEndBtn': function() { $('#dateEndTbx').datepicker('show'); },
                   

                };
            },
            refreshInterval : 60,
            bindings: 'data-bind',
            bindingSources: {},
            itemsColl: [],
            ItemsCollRealTime: [],
            subviews: {},
            viewParams: null,           
            isPaused: false,            
            AssignCoverModal : {},
            columnsRt: [],
            initialize: function () {
                var that = this;
                this.options.state = app.view_states.loading;
                this.options.onappend = (_.isFunction(this.options.onappend)) ? this.options.onappend : function () { };

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

                this.ItemsCollRealTime = new Screen.Collections.ItemsRealTime();

                // The cover-specific columns (C{N}S1, C{N}S2, C{N}ST) are built
                // dynamically AFTER the first fetch arrives -- the proc now
                // returns long-format rows and the collection sets
                // `coverNumbers` on itself. We seed the grid with just the
                // Timestamp column; getDynamicColumns() does the rest on each
                // fetch via gridApi.setColumnDefs().
                this.columnsRt = [
                    { field: 'Timestamp', headerName: 'Timestamp', showFilter: false,
                      fieldType: 'Datetime', format: 'MM/DD HH:mm' }
                ];
                this.agGridModuleRt = new CustomAgGridModule({
                    columnDefs: this.columnsRt,
                    rowData: [],
                    fileName:'covers-temperature-rt',
                    pagination:'hidden'
                });

                
                this.autoRefresh = {
                    enabled: false
                    , toid: null
                    , every: 1000 
                },
                this.model.set({
                    remainingSeconds: that.refreshInterval,
                    refreshIn: `Refresh In ${that.refreshInterval}`
                });
                this.bindEvents();
            },

            bindEvents: function () {
                this.listenTo(this.ItemsCollRealTime, 'fetch', this.collection_rt_ready);                
            },

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

                this.viewParams = viewParams;

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

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

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

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

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

                                that.applyBindings();

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

                                // Render the AgGridModule and append it to the container
                                that.agGridModuleRt.render();
                                that.$el.find('.grid-container-rt').append(that.agGridModuleRt.$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');
                               
                                that.model.set(fixedParams);

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

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

                                that._refreshRt({
                                    reset: true,
                                    params: _.extend(
                                        {},
                                        params,
                                        {
                                        }
                                    ),
                                });
                                that.startAutoRefresh();
                                that.refreshProcessesRt();
                                that.refreshBtnRt_click();
                            },
                            true,
                            customPath
                        );
                    },
                    customPath
                );
            },

            // ------------------------
            // -------- History -------
            // ------------------------
            refresh: function (viewParams) {

                var fixedParams = _.extend({}, Screen.Models.Main.prototype.defaults, viewParams);

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

                this._refresh({
                    reset: true,
                    params: _.extend(
                        {},
                        fixedParams,
                        {}
                    ),
                });
            },
     
            _refresh: function (opt) {
                this.itemsColl.reset();
                this.refreshProcesses(opt);
            },
            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
                });

            },
        
            refreshBtn_click: function (e) {
                try {
                    var params = this.model.toJSON();
                    app.router.navigate(
                        app.router.resolveURL(
                            app.router.currentModule,
                            _.extend(
                                {},
                                params,
                                {
                                    start: new moment(params.start, 'YYYY-MM-DD').format('YYYYMMDD'),
                                    end: new moment(params.end, 'YYYY-MM-DD').format('YYYYMMDD'),                                  
                                }
                            ),
                            false
                        ),
                        { trigger: false, }
                    );

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

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



            
            // --------------------------
            // -------- Real-Time -------
            // --------------------------
            resumeAutoRefresh: function() {
                this.isPaused = false;
                this._refreshRt(); // Immediately trigger a refresh
            },
            _refreshRt: function (opt) {
                var that = this;
                var currentSeconds = this.model.get('remainingSeconds');
            
                // Check if paused
                if (this.isPaused) {
                    // If paused, just reschedule the next check without changing anything
                    if (this.autoRefresh.enabled == true) {
                        if (this.autoRefresh.toid != null) {
                            clearTimeout(this.autoRefresh.toid);
                        }
                        this.autoRefresh.toid = setTimeout(
                            function () {
                                that._refreshRt();
                            },
                            this.autoRefresh.every // Run every 1 second
                        );
                    }
                    return; // Exit the function early if paused
                }
            
                // If not paused, proceed with normal refresh logic
                
                // Decrement the countdown
                currentSeconds = (currentSeconds > 0) ? currentSeconds - 1 : this.refreshInterval - 1;
                
                this.model.set({
                    remainingSeconds: currentSeconds,
                    refreshIn: `Refresh In ${currentSeconds}`
                });
            
                // Check if it's time to refresh the data (every 10 seconds)
                if (currentSeconds % 60 === 0 || opt) {
                    this.model.set({
                        refreshIn: `Refresh In ${60}`
                    });
            
                    this.ItemsCollRealTime.reset();
                    this.refreshProcessesRt(opt);
                    this.model.set('isLoadingRt', true);
                }
            
                // Schedule the next update
                if (this.autoRefresh.enabled == true) {
                    if (this.autoRefresh.toid != null) {
                        clearTimeout(this.autoRefresh.toid);
                    }
                    this.autoRefresh.toid = setTimeout(
                        function () {
                            that._refreshRt();
                        },
                        this.autoRefresh.every // Run every 1 second
                    );
                }
            },
                     
            collection_rt_ready: function () {
                try {
                    var that = this;
                    var newColumns = that.getDynamicColumns();

                    // Re-apply the column definitions ONLY when the set of
                    // covers actually changed. Re-applying on every refresh
                    // would blow away sort / scroll / filter state.
                    var newCoverKey = (that.ItemsCollRealTime.coverNumbers || []).join(',');
                    var columnsChanged = (newCoverKey !== that._lastCoverKey);
                    that._lastCoverKey = newCoverKey;

                    setTimeout(function () {
                        if (columnsChanged && that.agGridModuleRt && that.agGridModuleRt.gridApi) {
                            var api = that.agGridModuleRt.gridApi;
                            // AG Grid >= 31 removed setColumnDefs in favor of
                            // setGridOption('columnDefs', ...). Try the modern
                            // API first, fall back to the legacy one for older
                            // grid versions.
                            if (typeof api.setGridOption === 'function') {
                                api.setGridOption('columnDefs', newColumns);
                            } else if (typeof api.setColumnDefs === 'function') {
                                api.setColumnDefs(newColumns);
                            } else {
                                console.warn('covers-temperatures: gridApi has neither setGridOption nor setColumnDefs -- columns will not update dynamically.');
                            }
                            that.columnsRt = newColumns;
                        }
                        that.agGridModuleRt.setRowDataAsCollection(that.ItemsCollRealTime);
                        that.agGridModuleRt.hideOverlay();
                        that.model.set({ isLoadingRt: false });
                    }, 100);
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },

            getDynamicColumns: function () {
                // The collection's fetch handler discovered the cover numbers
                // present in the latest payload and stashed them on
                // `coverNumbers`. Build the AG Grid column hierarchy from that
                // -- not by scraping attribute keys off a row -- so a brand
                // new cover seen on this fetch shows up automatically.
                var coverNumbers = (this.ItemsCollRealTime && this.ItemsCollRealTime.coverNumbers) || [];

                // Pull the renderer off CustomAgGridModule (defined at the top
                // of this file). The constructor's initialize used to wire it
                // into the ST columns when they were declared statically; the
                // columns are now built here after construction, so the
                // renderer has to be attached inline.
                var statusCellRenderer = CustomAgGridModule.prototype.statusCellRenderer;

                var columns = [
                    { field: 'Timestamp', headerName: 'Timestamp', showFilter: false,
                      fieldType: 'Datetime', format: 'MM/DD HH:mm' }
                ];

                coverNumbers.forEach(function (cn) {
                    columns.push({
                        headerName: 'Cover ' + cn,
                        children: [
                            { field: 'C' + cn + 'S1', headerName: 'S. A',
                              flex: 1, cellClass: 'cover-first-column', minWidth: 80 },
                            { field: 'C' + cn + 'S2', headerName: 'S. B',
                              flex: 1, minWidth: 80 },
                            { field: 'C' + cn + 'ST', headerName: 'Status',
                              flex: 1, cellClass: 'cover-last-column', minWidth: 80,
                              cellRenderer: statusCellRenderer }
                        ]
                    });
                });

                return columns;
            },
            
                           
            refreshProcessesRt: function (options) {
                var that = this,
                    attrs = this.model.toJSON(),
                    opt = _.extend({}, options, { params: {}, });
                if ((opt.refresh == true) || (opt.reset == true)) {
                    this.model.set('isLoadingRt', true);
                    that.agGridModuleRt.showLoadingOverlay();  // Show loading overlay
                }

                this.ItemsCollRealTime.fetch({
                    start: attrs.start,
                    end: attrs.end
                });

            },

            refreshBtnRt_click: function (e) {
                try {
                    var params = this.model.toJSON();
                    
                    // Reset the countdown to 10
                    this.model.set({
                        remainingSeconds: 10,
                        refreshIn: 'Refresh In 10'
                    });


                    this._refreshRt({
                        reset: true,
                        params: _.extend(
                            {},
                            params,
                            {}
                        ),
                    });

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



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

            // ---------------------------------
            // -------- Common functions -------
            // ---------------------------------

            //Common functions
            append: function (container, el) {
                var that = this;
                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);

                    setTimeout(function() {
                        that.model.set({renderCompleted: true});
                    }, 1000);  
                }

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

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

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

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

                this.hideSubviews();

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

        Screen.Collections.ItemsRealTime = Backbone.Collection.extend({
            // Discovered cover numbers from the most recent fetch -- populated
            // by the long-format pivot below. The view's getDynamicColumns
            // reads this to build the AG Grid header hierarchy on each
            // refresh, so a brand-new cover appears without a page reload.
            coverNumbers: [],

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

                qp.Add('@timeZoneCode', 'CHAR', app.models.user.get('timezoneCode'));

                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.CAS.GetLastCoverTemperatures',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if (resp && resp.Table) {
                                    // ---------------------------------------------------------
                                    // Long-format input: [{Timestamp, CoverNumber, TempSensor1,
                                    //                    TempSensor2, Status}, ...]
                                    // Pivot to wide rows: one row per Timestamp, with C{N}S1 /
                                    // C{N}S2 / C{N}ST columns for each cover that appears.
                                    // ---------------------------------------------------------
                                    var pivotMap = {};
                                    var coverSet = {};
                                    _.each(resp.Table, function (r) {
                                        var cn = r.CoverNumber;
                                        coverSet[cn] = true;

                                        var key = r.Timestamp;
                                        if (!pivotMap[key]) {
                                            pivotMap[key] = { Timestamp: r.Timestamp };
                                        }
                                        pivotMap[key]['C' + cn + 'S1'] = r.TempSensor1;
                                        pivotMap[key]['C' + cn + 'S2'] = r.TempSensor2;
                                        pivotMap[key]['C' + cn + 'ST'] = r.Status;
                                    });

                                    var pivoted = _.values(pivotMap);
                                    // Most-recent first (the proc orders DESC but the pivot
                                    // step might reorder).
                                    pivoted.sort(function (a, b) {
                                        return new Date(b.Timestamp) - new Date(a.Timestamp);
                                    });

                                    that.coverNumbers = _.keys(coverSet)
                                        .map(function (n) { return Number(n); })
                                        .sort(function (a, b) { return a - b; });

                                    that.set(pivoted);
                                    that.trigger('fetch', that, pivoted);
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        console.error(new Error(resp.Message).stack);
                                        app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 5000, });
                                    }
                                    else {
                                        app.views.topMessages.showMessage('SERVER RESPONSE NOT VALID', { stay: 5000, });
                                        console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                    }
                                }
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        onFailure: function (resp) {
                            console.error(resp);
                        },
                        Secured: true,
                        // Switched from Async: false (deprecated, blocks UI) to
                        // Async: true. The grid renders with just the Timestamp
                        // column initially; cover columns are added when the
                        // first fetch resolves.
                        Async: true,
                    },
                    app.ConnectionStrings.app
                );
                return this;
            },

        });

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