define([
    'app',
    'js/templates-loader',
    'chart',
],

    function (app, T, Chart) {

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

        Screen.Models.TemperaturesHistoryModel = Backbone.Epoxy.Model.extend({
            defaults: {
                labels: [], // Array of date strings for the X-axis
                dataSensorA: [], 
                dataSensorB: [],  // Array of temperature values for the Y-axis
                maxTemperature: 1000, // Default maximum temperature for the Y-axis
                coverNumber: null,
                temperaturesTitle: null,
            },

            initialize: function () {
                this.fetchLastCoverTemperatures()
                this.set({temperaturesTitle: "Cover Number " + this.get('coverNumber')})
            },

            setData: function (labels, data) {
                this.set({ labels, data });
            },
            fetchLastCoverTemperatures: function() {
                var that = this;
                var qp = new Core.Database.QueryParameters();
                var fixedParameters = [
                    { Name: '@CoverNumber', Type: 'INT', Value: that.get('coverNumber'), }
                ];
                _.each(fixedParameters, function (qpParams) {
                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.CAS.GetTemperaturesByCover',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {

                                if (resp.Table) {
                                    that.labels = resp.Table.map(item => {
                                        return item.Timestamp;
                                    });

                                    that.dataSensorA = resp.Table.map(item => {
                                        return item.TempSensor1;
                                    });
                                    that.dataSensorB = resp.Table.map(item => {
                                        return item.TempSensor2;
                                    });
                                }
                                else {
                                    if ((resp) && (resp.Message)) {
                                        app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                        console.error(resp.Message);
                                        that.set({
                                            hasData: false,
                                            isLoading: false,

                                        });

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

                                }


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

        Screen.Views.TemperaturesHistoryModal = Backbone.Epoxy.View.extend({
            template: "modal-temperatures-history",
            id: "temperatures-history",
            className: "modal mmodal-temperatures-history hide fade",
            bindings: "data-bind",
            isCacheable: true,
            events: function () {
                return {
                    "keypress": this.modal_keypress,
                    "show.bs.modal": this.modal_show,
                    "shown.bs.modal": this.modal_shown,
                    "hidden.bs.modal": this.modal_hidden,
                };
            },
            container: null,
            disposed: false,
            isRendered: false,
            preventDispose: false,
            visible: false,
            data: null,
            initialize: function (options) {
                _.extend(this, options);
                var data = options.data;
                if (!this.model) {
                    this.model = new Screen.Models.TemperaturesHistoryModel({
                         coverNumber: data.CoverNumber,
                        temperaturesTitle: `Temperature History for Cover ${data.CoverNumber}`
                    });
                }
                
                this.model.set({
                    coverNumber: data.CoverNumber,
                    temperaturesTitle: `Temperature History for Cover ${data.CoverNumber}`
                });

               // this.bus = options.bus;
                this.bindEvents();

                return this;
            },

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

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

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

                        //const labels = this.model.get('labels');
                        //const data = this.model.get('data');
                        const maxTemperature = that.model.get('maxTemperature');

                       

                        // Create the canvas element if it doesn't exist
                        if (!that.$el.find('canvas').length) {
                            that.$el.append('<canvas id="temperatureChart"></canvas>');
                        }

                        const ctx = that.$('#temperatureChart')[0].getContext('2d');

                        // Destroy the previous chart instance if it exists
                        if (this.chart) {
                            this.chart.destroy();
                        }

                        // Initialize the chart
                        this.chart = new Chart(ctx, {
                            type: 'line',
                            data: {
                                labels: that.model.labels.map((item, index, array) => {
                                    // Extract the Unix timestamp from the string
                                    const match = item.match(/\/Date\((\d+)\)\//);
                                    if (!match || match.length < 2) {
                                        console.error("Invalid date format:", item);
                                        return ""; // Return an empty label if the format is incorrect
                                    }
                                
                                    // Convert the extracted timestamp to a number and create a Date object
                                    const timestamp = parseInt(match[1], 10);
                                    const date = new Date(timestamp);
                                
                                    // Check if the date is valid
                                    if (isNaN(date.getTime())) {
                                        console.error("Invalid date:", timestamp);
                                        return ""; // Return an empty label if the date is invalid
                                    }
                                
                                    // Get the current day, hour, and minute
                                    const currentDay = date.toLocaleDateString([], { month: '2-digit', day: '2-digit' });
                                    const currentTime = date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
                                
                                    // Check the previous label's day (if it exists)
                                    if (index > 0) {
                                        const prevMatch = array[index - 1].match(/\/Date\((\d+)\)\//);
                                        if (prevMatch && prevMatch.length >= 2) {
                                            const prevTimestamp = parseInt(prevMatch[1], 10);
                                            const prevDate = new Date(prevTimestamp);
                                            const prevDay = prevDate.toLocaleDateString([], { month: '2-digit', day: '2-digit' });
                                
                                            // If the day is the same, return only the time
                                            if (currentDay === prevDay) {
                                                return currentTime;
                                            }
                                        }
                                    }
                                
                                    // If the day changes or it's the first label, show the day and time
                                    return `${currentDay} ${currentTime}`;
                                }), // Use all timestamps
                                datasets: [{
                                    label: 'Sensor A (°F)',
                                    data: that.model.dataSensorA, // Use all temperature values
                                    fill: false,
                                    borderColor: '#e74c3c',
                                    backgroundColor: 'rgba(231, 76, 60, 0.3)',
                                    pointBorderColor: '#e74c3c',
                                    pointBackgroundColor: '#fff',
                                    pointRadius: 5,
                                    tension: 0.4
                                },
                                {
                                    label: 'Sensor B (°F)',
                                    data: that.model.dataSensorB, // Use all temperature values
                                    fill: false,
                                    borderColor: '#4db5ff',
                                    backgroundColor: 'rgba(131, 202, 252, 0.3)',
                                    pointBorderColor: '#4db5ff',
                                    pointBackgroundColor: '#fff',
                                    pointRadius: 5,
                                    tension: 0.4
                                }]
                            },
                            options: {
                                responsive: true,
                                plugins: {
                                    legend: {
                                        display: true,
                                        position: 'top'
                                    }
                                },
                                scales: {
                                    y: {
                                        title: {
                                            display: true,
                                            text: 'Temperature (°F)'
                                        },
                                        min: 0,
                                        max: maxTemperature
                                    },
                                    x: {
                                        title: {
                                            display: true,
                                            text: 'Time'
                                        },
                                        type: 'category',
                                        ticks: {
                                            autoSkip: true, // Enable auto-skip
                                            maxTicksLimit: 12, // Limit the maximum number of labels
                                            minRotation: 0, // Ensures horizontal text
                                            maxRotation: 0
                                        }
                                    }
                                }
                            }
                        });



                        that.isRendered = true;
                        that.trigger("render");


                    }, true, customPath);

                }, customPath, "modal_temperatures_history");

            },



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

                return this;
            },

            bindEvents: function () {
                this.listenToOnce(this, "render", this.view_render);
            },

            close: function () {
                if (this.disposed == false) {
                    if (this.visible == true) {
                        this.hide();
                    }
                    else {
                        this.trigger('close');

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

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

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

                this.fixedParameters = [
                    { Name: '@productId', Type: 'INT', Value: params.productId, },
                    { Name: '@Printer', Type: 'INT', Value: params.printer, },
                    { Name: '@ReasonPhraseId', Type: 'INT', Value: params.reasonPhraseId, },
                    { Name: '@Comments', Type: 'VARCHAR', Value: params.comments, },
                    { Name: '@Employee', Type: 'VARCHAR', Value: params.employee, },
                    { Name: '@Length', Type: 'FLOAT', Value: params.pieceLength, },

                ];
                _.each(this.fixedParameters, function (qpParams) {
                    qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                });
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.CAS.UpsertTaggingCommand',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {

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

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

                    if (!this.preventDispose)
                        this.close();
                    else
                        this.preventDispose = false;
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            modal_show: function (e) {
                try {
                    this.visible = true;
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            modal_shown: function (e) {
                try {
                    this.$el.find(".autofocus").focus();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            view_render: function () {
                try {
                    //this.renderMultipicker();
                    this.show();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
        });
        // Required, return the module for AMD compliance.
        return Screen;

    });