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

    'components/ag-grid/ag-grid-module',
    'backgrid/moment-cell',
],
    function (app, T, Backgrid, moment, AgGridModule) {

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

        Screen.Models.Main = Backbone.Epoxy.Model.extend({
            defaults: {
                start: new moment().subtract(7, 'days').format('YYYY-MM-DD'),
                end: new moment().format('YYYY-MM-DD'),

                ladleId: -1,
                ladles: [{ label: 'All Ladles', value: -1 }],

                hasData: false,
                isLoading: false,
                isPageLoading: 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, };
                    },
                },
            },
            fetchLadles: function () {
                var that = this;
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.LAD.GetLadles',
                    null,
                    {
                        onSuccess: function (resp) {
                            try {
                                if ((resp) && (resp.Table)) {
                                    var records = _.map(resp.Table, function (item) { return { label: item.Name, value: item.Id } });
                                    records.unshift({ label: 'All Ladles', value: -1 });
                                    that.set('ladles', records);
                                }
                                else {
                                    if ((resp) && (resp.Message))
                                        console.error(resp.Message);
                                    else
                                        console.error('Server response not valid.');
                                }
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        },
                        Secured: true,
                        async: false,
                    },
                    app.ConnectionStrings.app
                );
            },
        });

        var CustomAgGridModule = AgGridModule.extend({
            initialize: function (options) {
                this.bus = options.bus;
                this.itemsColl = options.itemsColl;
                this.parentView = options.parentView;

                this.columnDefs = [
                    { field: 'LadleId', headerName: 'Ladle', flex: 1, showFilter: true },
                    { field: 'HeatId', headerName: 'Heat Id', flex: 1, showFilter: true },
                    { field: 'TapTime', headerName: 'Tap Time', flex: 1, minWidth: 120, showFilter: false, fieldType: 'Datetime', format: 'MM/DD/YY HH:mm' },
                    { field: 'TapTemperature', headerName: 'Tap Temp', flex: 1, showFilter: false },
                    { field: 'SteelWeight', headerName: 'Steel Weight', flex: 1, showFilter: false },
                    { field: 'LadleSlideGate', headerName: 'Slide Gate', flex: 1, showFilter: false },
                    { field: 'MountingPlate', headerName: 'Mounting Plate', flex: 1, showFilter: false },
                    { field: 'PlateAssembly', headerName: 'Plate Assembly', flex: 1, showFilter: false },
                    { field: 'UpperNozzle', headerName: 'Upper Nozzle', flex: 1, showFilter: false },
                    { field: 'WorkingLining', headerName: 'Working Lining', flex: 1, showFilter: false },
                    { field: 'PorousPlugNorth', headerName: 'Plug North', flex: 1, showFilter: false },
                    { field: 'PorousPlugSouth', headerName: 'Plug South', flex: 1, showFilter: false },
                    { field: 'SentBy', headerName: 'Sent By', flex: 1, showFilter: false },
                    { field: 'CompletedBy', headerName: 'Completed By', flex: 1, showFilter: false },
                    { field: 'Comments', headerName: 'Comments on Plugs or Plates', flex: 2, minWidth: 200, showFilter: false },
                    {
                        headerName: 'Edit',
                        field: 'edit',
                        flex: 0.5,
                        minWidth: 60,
                        showFilter: false,
                        cellRenderer: this.editCellRenderer.bind(this),
                        cellStyle: { display: 'flex', justifyContent: 'center', alignItems: 'center' }
                    }
                ];

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

                // Initialize ag-Grid
                AgGridModule.prototype.initialize.call(this, options);
            },

            // Override exportToExcel to exclude the 'edit' column
            exportToExcel: function (onlySelected) {
                if (!this.gridApi) {
                    console.error('Grid API is not available');
                    return;
                }

                // Get all column keys except 'edit'
                var columnKeys = this.columnDefs
                    .filter(function (colDef) { return colDef.field !== 'edit'; })
                    .map(function (colDef) { return colDef.field; });

                var params = {
                    fileName: this.getExportFileName(),
                    onlySelected: onlySelected,
                    columnKeys: columnKeys
                };
                this.gridApi.exportDataAsExcel(params);
            },

            editCellRenderer: function (params) {
                var that = this;
                var container = document.createElement('div');
                container.className = 'flex justify-center';
                container.style.cursor = 'pointer';

                var editBtn = document.createElement('button');
                editBtn.className = 'text-blue-600 hover:text-blue-800';
                editBtn.innerHTML = '<i class="fa fa-pencil" style="font-size: 16px;"></i>';
                editBtn.title = 'Edit Comments';

                editBtn.addEventListener('click', function (e) {
                    e.stopPropagation();
                    if (that.parentView) {
                        that.parentView.openCommentModal(params.data);
                    }
                });

                container.appendChild(editBtn);
                return container;
            }
        });


        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'ref-ladle-history',
            id: 'ref-ladle-history',
            title: 'Ladle Equipment History',
            events: function () {
                return {
                    'click #refreshBtn': this.refreshBtn_click,
                    'click #exportExcelBtn': this.exportToExcel,
                    'click #calendarStartBtn': this.calendarStartBtn_click,
                    'click #calendarEndBtn': this.calendarEndBtn_click,
                    'click #modalSaveBtn': this.saveComment,
                    'click #modalCancelBtn': this.closeCommentModal,
                };
            },
            bindings: 'data-bind',
            bindingSources: null,
            grids: null,
            itemsColl: null,
            subviews: null,
            viewParams: null,
            currentEditRow: 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();

                // Init AgGridModule:
                this.agGridModule = new CustomAgGridModule({
                    itemsColl: this.itemsColl,
                    bus: this.bus,
                    rowData: [],
                    onChange: this.handleGridChange.bind(this),
                    onRemove: this.handleGridRemove.bind(this),
                    fileName: 'ladle-equipment-history',
                    screenTitle: 'Ladle Equipment History',
                    isPageLoading: that.model.get('isPageLoading'),
                    parentView: this,
                });
                this.grids = {};

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

                this.bindingSources = {};

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

                this.model.fetchLadles();

                this.bindEvents();
                this.bus = _.extend({}, Backbone.Events);
            },

            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, 'fetch', this.processes_ready)
                    .listenTo(this.model, 'triggerFetch', this.refreshBtn_click);
            },

            _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(fixedParams.start, 'YYYYMMDD').format('YYYY-MM-DD');
                if (viewParams.end)
                    fixedParams.end = new moment(fixedParams.end, 'YYYYMMDD').format('YYYY-MM-DD');
                if (viewParams.ladleId)
                    fixedParams.ladleId = (viewParams.ladleId != '-' && viewParams.ladleId != null) ? parseInt(viewParams.ladleId, 10) : -1;

                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/ref/' + 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();

                                //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 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 (viewParams.ladleId)
                                    fixedParams.ladleId = (viewParams.ladleId != '-' && viewParams.ladleId != null) ? parseInt(viewParams.ladleId, 10) : -1;

                                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();
                            that.model.set({
                                hasData: (that.itemsColl.length > 0),
                                isLoading: false,
                            });
                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },

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

                this.itemsColl.fetch({
                    start: attrs.start,
                    end: attrs.end,
                    ladleId: attrs.ladleId === -1 ? null : attrs.ladleId,
                    refresh: true,
                });
            },

            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'),
                                    ladleId: (params.ladleId == null || params.ladleId == "" || params.ladleId == -1) ? '-' : params.ladleId,
                                }
                            ),
                            false
                        ),
                        { trigger: false, }
                    );

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

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

            // Modal functions
            openCommentModal: function (rowData) {
                this.currentEditRow = rowData;
                var $modal = this.$el.find('#commentModal');

                // Populate modal fields
                this.$el.find('#modalHeatId').text(rowData.HeatId || '');
                this.$el.find('#sentByInput').val(rowData.SentBy || '');
                this.$el.find('#completedByInput').val(rowData.CompletedBy || '');
                this.$el.find('#commentsInput').val(rowData.Comments || '');

                // Show modal
                $modal.removeClass('hidden');
            },

            closeCommentModal: function () {
                this.currentEditRow = null;
                var $modal = this.$el.find('#commentModal');
                $modal.addClass('hidden');

                // Clear fields
                this.$el.find('#sentByInput').val('');
                this.$el.find('#completedByInput').val('');
                this.$el.find('#commentsInput').val('');
            },

            saveComment: function () {
                var that = this;

                if (!this.currentEditRow) {
                    console.error('No row selected for editing');
                    return;
                }

                var heatId = this.currentEditRow.HeatId;
                var sentBy = this.$el.find('#sentByInput').val().trim();
                var completedBy = this.$el.find('#completedByInput').val().trim();
                var comments = this.$el.find('#commentsInput').val().trim();

                var qp = new Core.Database.QueryParameters();
                qp.Add('@HeatId', 'VARCHAR', heatId);
                qp.Add('@SentBy', 'VARCHAR', sentBy || null);
                qp.Add('@CompletedBy', 'VARCHAR', completedBy || null);
                qp.Add('@Comments', 'VARCHAR', comments || null);

                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.REF.UpsertLadleHistoryComment',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if (resp && resp.Success !== false) {
                                    app.views.topMessages.showMessage('Comment saved successfully', { stay: 3000 });
                                    that.closeCommentModal();
                                    that.refreshBtn_click();
                                }
                                else {
                                    if (resp && resp.Message) {
                                        app.views.topMessages.showMessage(resp.Message, { stay: 5000 });
                                        console.error(resp.Message);
                                    }
                                    else {
                                        app.views.topMessages.showMessage('Failed to save comment', { stay: 5000 });
                                        console.error('Server response not valid.');
                                    }
                                }
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        },
                        onFailure: function (resp) {
                            app.views.topMessages.showMessage('Failed to save comment', { stay: 5000 });
                            console.error(resp);
                        },
                        Secured: true,
                        Async: true,
                    },
                    app.ConnectionStrings.app
                );
            },

            exportToExcel: function () {
                if (this.agGridModule) {
                    this.agGridModule.exportToExcel(false);
                }
            },

            //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: 'DATE', Value: params.start, },
                        { Name: '@end', Type: 'DATE', Value: params.end, },
                        { Name: '@ladleId', Type: 'INT', Value: params.ladleId, },
                    ];
                }
                this.isFetching = true;

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

                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.REF.GetLadleEquipmentHistory',
                    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);
                        },
                        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;
    });
