//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',
    'modules/modal',
    'chartjs-date-fns-adapter',
    'backgrid/moment-cell',
    'backgrid/grouped-columns',
    'js/multiselect/virtual-select.min',
    "js/jquery.floatThead/jquery.floatThead",

],
    function (app, T, Backgrid, Modal) {

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

    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {
            hasData: true,
            isLoading: false,
            materialSelected: null,
        },
        initialize: function () {
            this.materialsColl = new Screen.Collections.ItemsColl();
            this.materialsToCommoditiesColl = new Screen.Collections.ItemsColl();
            this.commodities = new Screen.Collections.ItemsColl();   
        },
        fetch: function (params) {
            var that = this;
            var qp = new Core.Database.QueryParameters();

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

                            if (resp && resp.Table) {           
                                that.materialsToCommoditiesColl.setDataColl(resp.Table);
                                that.materialsColl.setDataColl(resp.Table1);
                                that.commodities.setDataColl(resp.Table2);

                            }
                            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); }
                    },
                    Secured: true,
                },
                app.ConnectionStrings.app
            );

            return this;

        },
        deleteLink: function (params) {
            var that = this;
            var qp = new Core.Database.QueryParameters();
            qp.Add('@ScrapMaterialName', 'VARCHAR', params.ScrapMaterialName);
            qp.Add('@CommodityId', 'INT', params.CommodityId);
            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.SCRAP.DeleteLinkMaterialCommodity',
                qp,
                {
                    onSuccess: function (resp) {
                        try {

                            if ((resp)) {
                            }
                            else {
                                if ((resp) && (resp.Message)) {
                                    app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                    console.error(resp.Message);
                                } else {
                                    app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                    console.error(resp.Message);
                                }
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onError: function () {
                        if (options.callback != null && _.isFunction(options.callback))
                            options.callback.call(this, that);
                    }, 
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );

            return this;
        },
        upsertLink: function (params) {
            var that = this;
            var qp = new Core.Database.QueryParameters();
            qp.Add('@ScrapMaterialName', 'VARCHAR', params.ScrapMaterialName);
            qp.Add('@CommodityId', 'INT', params.CommodityId);
            qp.Add('@Percentage', 'INT', params.Percentage);
            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.SCRAP.UpsertLinkMaterialCommodity',
                qp,
                {
                    onSuccess: function (resp) {
                        try {

                            if ((resp)) {
                            }
                            else {
                                if ((resp) && (resp.Message)) {
                                    app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                    console.error(resp.Message);
                                } else {
                                    app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                    console.error(resp.Message);
                                }
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onError: function () {
                        if (options.callback != null && _.isFunction(options.callback))
                            options.callback.call(this, that);
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );

            return this;
        },
        handleMaterial: function (params) {
            var that = this;
            var qp = new Core.Database.QueryParameters();
            qp.Add('@ScrapMaterialName', 'VARCHAR', params.ScrapMaterialName);
            qp.Add('@Action', 'VARCHAR', params.Action);
            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.SCRAP.HandleMaterial',
                qp,
                {
                    onSuccess: function (resp) {
                        try {

                            if ((resp)) {
                                app.views.topMessages.showMessage('Material: ' + params.ScrapMaterialName +
                                    (params.Action == 'DELETE' ? ' Disallowed': ' Added')
                                    , { stay: 5000, });
                            }
                            else {
                                if ((resp) && (resp.Message)) {
                                    app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                    console.error(resp.Message);
                                } else {
                                    app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                    console.error(resp.Message);
                                }
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onError: function () {
                        if (options.callback != null && _.isFunction(options.callback))
                            options.callback.call(this, that);
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );

            return this;
        },
        
    });

        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'materials-commodities',
            id: 'materials-commodities',
            title: 'Materials Commodities',
            isCacheable: false,
            events: function () {
                return {
                    'click #saveChangesBtn': this.saveChanges_click,
                    'click #cancelChangesBtn': this.cancelChanges_click,
                    'keypress input[type="number"]': this.keyPress_handle,
                };
            },
            bindings: 'data-bind',
            subviews: null,
            viewParams: null,
            autoRefresh: null,
            pauseTimer: false,

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

                var that = this;
                this.model = new Screen.Models.Main();

                this.autoRefresh = {
                    enabled: null
                    , toid: null
                    , every: 5 * 1000
                };
                this.bus = _.extend({}, Backbone.Events);
                this.bus.on("modalAcceptBtn", this.onModalAcceptBtn, this);
                this.bus.on("modalCancelBtn", this.refresh, this);
                this.bindEvents();

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

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

                var customPath = '/app/custom-screens/' + this.template + '/';

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

                        app.getI18NJed(
                            that,
                            that.template,
                            function (i18nJED) {
                                that.options.i18n[that.template] = i18nJED;
                                that.$el.html(tmp());


                                var gridMaterials = new Backgrid.Grid({
                                    className: 'backgrid table table-hover table-condensed table-materials',
                                    columns: [

                                        {
                                            name: 'Name',
                                            editable: false,
                                            label: 'Material Name',
                                            cell: Backgrid.StringCell.extend({ 
                                                className: 'string-cell align-center-cell ',
                                                events: {
                                                    'click': 'cellClicked'
                                                },
                                                cellClicked: function (e) {
                                                    
                                                   
                                                    if (this.model.get('isAllowed')) {
                                                        var $row = $(e.target).closest('tr');
                                                        $row.siblings().removeClass('highlight-material');
                                                        $row.addClass('highlight-material');
                                                        that.model.set('materialSelected', this.model.get('Name'));
                                                        that.renderCommoditiesForMaterial();
                                                    }
                                                    else {
                                                        app.views.topMessages.showMessage("Material is Disallowed.", { stay: 5000, });
                                                    }
                                                   
                                                }
                                            }),
                                            headerCell: Backgrid.HeaderCell.extend({
                                                render: function () {
                                                    var button = $('<button class="btn btn-primary btn-sm add-material">Add</button>');
                                                    var title = $('<span class="material-label">' + this.column.get('label') + '</span>');

                                                    // Append the button and title to the header cell
                                                    this.$el.append(button).append(title);

                                                    return this;
                                                },
                                                events: {
                                                    'click .add-material': 'onAddMaterial'
                                                },
                                                onAddMaterial: function (e) {
                                                    e.preventDefault();
                                                    that.addNewMaterialModal(); 
                                                }
                                            })
                                        },
                                        {
                                            name: '',
                                            label: '',
                                            cell: Backgrid.Cell.extend({
                                                className: 'checkbox-cell',
                                                events: {
                                                    'change input[type="checkbox"]': 'onCheckboxChange'
                                                },
                                                render: function () {
                                                    var materialChecked = this.model.get('isAllowed');
                                                    var checkbox = $('<input type="checkbox" />');
                                                    checkbox.prop('checked', materialChecked);
                                                    this.$el.empty().append(checkbox);
                                                    return this;
                                                },
                                                onCheckboxChange: function (e) {
                                                    var materialChecked = $(e.target).is(':checked');
                                                    //this.model.set('materialChecked', materialChecked);

                                                    if (!materialChecked) {
                                                        that.deleteModal(this.model);
                                                    }
                                                    else {
                                                        that.allowMaterialModal(this.model);

                                                        this.model.set('isAllowed', true);
                                                    }
                                                }
                                            })
                                        }
                                        
                                    ],
                                    collection: that.model.materialsColl,
                                });


                                that.$el.find('.main-info-grid-container').append(gridMaterials.render().el);
                                var $table = that.$el.find('.main-info-grid-container table');

                                $table.on('scroll', function () {
                                    var $header = $table.find('thead');
                                    var scrollLeft = $table.scrollLeft();
                                    $header.css('transform', 'translateX(' + -scrollLeft + 'px)');
                                });
                                that.applyBindings();

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

                                that.refresh();

                                //that.startAutoRefresh();

                            },
                            true,
                            customPath
                        );
                    },
                    customPath
                );
            },
            onModalAcceptBtn: function (selectedMaterialName) {
                var that = this;
                that.model.handleMaterial({ ScrapMaterialName: selectedMaterialName, Action: 'DELETE' });
                that.refresh();
            },

            allowMaterialModal: function (model) {
                var that = this;
               

                    modal = new Modal.Views.Main({
                        focusOk: false,
                        focusSelector: '#btn-cancel',
                        title: 'Allow Material',
                        message: 'Are you sure you want to allow Material ' + model.get('Name') + '?',
                        buttons_type: "CONTINUE-CANCEL",
                    });
                    this.listenToOnce(modal, "continue", function (modal) {
                        try {
                            that.model.handleMaterial({ ScrapMaterialName: model.get('Name'), Action: 'ALLOW' });
                            that.refresh();
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    });
                    modal.show();
            },

            
            addNewMaterialModal: function () {
                var that = this;
                var modal = new Modal.Views.Main({
                    id: "add-material-modal"
                    , title: 'Add New Material'
                    , content: this.$el.find("#modal_add_material").html()
                    , allowCancel: true
                    , buttons_type: "CONTINUE-CANCEL"
                    , focusOk: false,
                });

                this.listenToOnce(modal, "continue", function (modal) {
                    try {
                        var inputValue = $('#newMaterialName').val();
                        that.model.handleMaterial({ ScrapMaterialName: inputValue, Action: 'INSERT' });
                        a
                        that.refresh();
                    }
                    catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                });

                modal.show();
                $(document).on('keyup', '#newMaterialName', function () {
                    $(this).val($(this).val().toUpperCase()); // Convert value to uppercase
                });
            },
            deleteModal: function (model) {
                

                var modal = new Screen.Views.RecipesModal({
                    row: model,
                    bus: this.bus,
                    //unassign: unassign,
                });

                modal.show();
            },
            renderCommoditiesForMaterial: function () {
                var that = this;
                var materialsToCommoditiesColl = that.model.materialsToCommoditiesColl;
                var materialSelected = that.model.get('materialSelected');
                var gridMaterialsToCommodities = new Backgrid.Grid({
                    className: 'backgrid table table-hover table-condensed',
                    row: Backgrid.Row.extend({
                        className: 'backgrid-row',
                        render: function () {
                            Backgrid.Row.prototype.render.apply(this, arguments);
                            var existsInMaterials = this.model.get('existsInMaterials');

                            if (existsInMaterials) {
                                this.$el.addClass('highlight-commodity');
                                this.model.set('isChecked', true);
                            } else {
                                this.$el.removeClass('highlight-commodity');
                            }

                            return this;
                        }
                    }),
                    columns: [

                        {
                            name: '',
                            label: '',
                            editable: false,
                            sortable: false,
                            cell: Backgrid.Cell.extend({
                                className: 'checkbox-cell',
                                render: function () {
                                    var that = this;
                                    var commodityName = this.model.get('CommodityName');
                                    var isChecked = this.model.get('isChecked');
                                    var existsInMaterials = materialsToCommoditiesColl.some(function (material) {
                                        return (material.get('CommodityName') === commodityName) && (material.get('ScrapMaterialName') === materialSelected);
                                    });

                                    var checkbox = $('<input type="checkbox" />');
                                    checkbox.prop('checked', existsInMaterials);

                                    //enable or disable percentage
                                    function togglePercentageInput(enabled) {
                                        var percentageInput = that.$el.closest('tr').find('input[type=number]');
                                        if (enabled) {
                                            
                                            percentageInput.prop('disabled', !enabled);

                                            // set value automatically to Percentage Input
                                            var checkedRows = that.model.collection.filter(x => (x.get('isChecked') == true) && (x.get('CommodityName') != commodityName));
                                            var totalCheckedPercentage = checkedRows.reduce(function (acc, material) {
                                                var percentage = parseFloat(material.get('Percentage'));
                                                return isNaN(percentage) ? acc : acc + percentage;
                                            }, 0);

                                            var remainingPercentage = 100 - totalCheckedPercentage;

                                            percentageInput.val(remainingPercentage);

                                        }
                                        else {
                                            percentageInput.prop('disabled', enabled);
                                            percentageInput.val(0);
                                        }
                                    }


                                    // Add event listener to track checkbox change
                                    checkbox.on('change', function () {
                                        var checked = $(this).is(':checked');
                                        that.model.set('isChecked', checked); // Update model with checkbox state
                                        var row = $(this).closest('tr');
                                        row.toggleClass('highlight-commodity', checked);

                                        // Enable/disable percentage input based on checkbox state
                                        togglePercentageInput(checked);
                                    });

                                    this.$el.empty().append(checkbox);
                                    this.model.set('existsInMaterials', existsInMaterials);
                                    return this;
                                }
                            })
                        },
                        {
                            name: 'CommodityName',
                            editable: false,
                            label: 'Commodity',
                            cell: Backgrid.StringCell.extend({
                                className: 'string-cell align-center-cell ',
                            }),
                        },
                        {
                            name: '',
                            label: 'Percentage',
                            editable: false,
                            cell: Backgrid.NumberCell.extend({
                                className: 'number-cell align-center-cell ',
                                render: function () {
                                    var that = this;
                                    var commodityName = this.model.get('CommodityName');
                                   
                                    var matchedMaterial = materialsToCommoditiesColl.find(function (material) {
                                        return material.get('CommodityName') === commodityName && material.get('ScrapMaterialName') === materialSelected;
                                    });
                                    
                                    var percentage = matchedMaterial ? matchedMaterial.get('Percentage') : 0;
                                    this.model.set('Percentage', percentage);
                                    

                                    // Create an input field for editing
                                    var inputEl = $('<input type="number" />');
                                    inputEl.val(percentage); // Set the initial value
                                    inputEl.prop('disabled', !this.model.get('existsInMaterials'));

                                    inputEl.on('change', function () {
                                        var newPercentage = parseFloat($(this).val());
                                        if (newPercentage !== percentage) {
                                            percentage = newPercentage;
                                            that.model.set('Percentage', newPercentage);
                                        }
                                    });

                                    // Empty the cell and append the input field
                                    this.$el.empty().append(inputEl);
                                    return this;
                                }
                            }),
                        }
                    ],
                    collection: that.model.commodities,
                });
                gridMaterialsToCommodities.render();
                // Reorder the rows based on checkbox status
                var $tbody = gridMaterialsToCommodities.$el.find('tbody');
                var $rows = $tbody.children('tr');

                $rows.sort(function (a, b) {
                    var $checkboxA = $(a).find('input[type="checkbox"]');
                    var $checkboxB = $(b).find('input[type="checkbox"]');

                    var isCheckedA = $checkboxA.is(':checked');
                    var isCheckedB = $checkboxB.is(':checked');

                    // Sort checked rows to appear first
                    if (isCheckedA && !isCheckedB) {
                        return -1;
                    } else if (!isCheckedA && isCheckedB) {
                        return 1;
                    } else {
                        return 0;
                    }
                });

                $tbody.append($rows);
                var $table = that.$el.find('.materialToCommodities-grid-container table');

                $table.on('scroll', function () {
                    var $header = $table.find('thead');
                    var scrollLeft = $table.scrollLeft();
                    $header.css('transform', 'translateX(' + -scrollLeft + 'px)');
                });
                that.$el.find('.materialToCommodities-grid-container').empty().append(gridMaterialsToCommodities.el);

                

                //that.$el.find('.materialToCommodities-grid-container').append(gridMaterialsToCommodities.render().el);

            },
            cancelChanges_click: function () {
                var that = this;

                that.model.set('materialSelected', null);
                that.$el.find('.materialToCommodities-grid-container').empty();
                that.refresh();
            },
            keyPress_handle: function (e) {
                var that = this;
                if (e.which === 13 || e.keyCode === 13) {
                    e.preventDefault();
                    this.saveChanges_click();
                }
                
            },
            saveChanges_click: function () {
                var that = this;

                var mappedValues = [];

                // Select all rows within the grid container and iterate over them
                $('.materialToCommodities-grid-container .backgrid-row').each(function () {
                    var row = $(this);

                    // only add the checked
                    if (row.find('input[type="checkbox"]').prop('checked')) {

                    // Retrieve data from specific cells within the row
                    var commodityName = row.find('td:nth-child(2)').text(); 
                        var percentage = row.find('input[type="number"]').val(); 
                    var isChecked = row.find('input[type="checkbox"]').prop('checked'); 
                    var value = row.find('input[type="checkbox"]').val(); 

                    // Create an object with data from columns and checkbox
                    var rowData = {
                        CommodityName: commodityName,
                        Percentage: percentage,
                        CheckboxValue: value, 
                        CheckboxChecked: isChecked
                    };

                        mappedValues.push(rowData); // Push the object to the array
                    }
                });


                //check if percentage is > than 100%
                var totalPercentage = mappedValues.reduce(function (accumulator, currentValue) {
                    return accumulator + parseInt(currentValue.Percentage);
                }, 0);

                if (totalPercentage > 100) {
                    app.views.topMessages.showMessage('Total Percentage is greater than 100%', { stay: 5000, });
                }
                else {
                    this.handleDelete(mappedValues);
                    this.handleUpdate(mappedValues);

                    app.views.topMessages.showMessage('Material '+that.model.get('materialSelected')+ ' updated', { stay: 6000, });
                    that.refresh();
                    
                }

                
            },

            handleDelete: function (mappedValues) {
                var that = this;
                //check values to Delete first (validate in the main collection if there is any element different that the mapped)
                var mappedCommodityNames = mappedValues.map(function (item) {
                    return item.CommodityName;
                });

                // Filter materialsToCommoditiesColl based on CommodityName not present in mappedCommodityNames ( this means it was unchecked)
                var modelsToDelete = that.model.materialsToCommoditiesColl.filter(function (material) {
                    return (
                        material.get('ScrapMaterialName') === that.model.get('materialSelected') &&
                        !mappedCommodityNames.includes(material.get('CommodityName'))
                    );
                });

                if (modelsToDelete.length != 0) {
                    _.each(modelsToDelete, function (model) {
                        var params = { ScrapMaterialName: model.get('ScrapMaterialName'), CommodityId: model.get('CommodityId') };
                        that.model.deleteLink(params);
                    });
                }
            },
            handleUpdate: function (mappedValues) {
                var that = this;
                // Get the ScrapMaterialName from the main model
                var materialSelected = that.model.get('materialSelected');

                // Filter materialsToCommoditiesColl based on ScrapMaterialName and create a map for efficient comparison
                var materialCommodityMap = {};
                that.model.materialsToCommoditiesColl.each(function (material) {
                    if (material.get('ScrapMaterialName') === materialSelected) {
                        materialCommodityMap[material.get('CommodityName')] = material.get('Percentage');
                    }
                });

                // Find models from mappedValues that are missing in materialsToCommoditiesColl
                var modelsToUpsert = mappedValues.filter(function (mappedItem) {
                    var commodityName = mappedItem.CommodityName;
                    var percentageInMappedValues = mappedItem.Percentage;
                    var percentageInMaterials = materialCommodityMap[commodityName];

                    // Check if the model is missing or if Percentage differs
                    return (!percentageInMaterials || Number(percentageInMaterials) !== Number(percentageInMappedValues));
                });

                if (modelsToUpsert.length != 0) {
                    _.each(modelsToUpsert, function (model) {
                        var params = {
                            ScrapMaterialName: materialSelected,
                            CommodityId: that.model.commodities.filter(x => x.get('CommodityName') == model.CommodityName)[0].get('Id'),
                            Percentage: model.Percentage
                        };
                        that.model.upsertLink(params);
                    });
                }
                
            },

            refresh: function (isAutoRefresh) {
                if (!isAutoRefresh) {
                    this.model.set({
                        isLoading: true,
                        hasData: false,
                    });
                }
                else {
                    this.model.set({
                        isLoading: false,
                        hasData: true,
                    });
                }
                
                this.model.fetch();
                this.$el.find('.materialToCommodities-grid-container').empty();
            },
            process_fetched: function () {
                this.model.set({
                    isLoading: false,
                    hasData: true,
                });
            },

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

        },
            //Auto refresh
            _refresh: function (opt) {
                if (this.autoRefresh.toid != null) {
                    clearTimeout(this.autoRefresh.toid);
                    this.autoRefresh.toid = null;
                }

                if (!this.pauseTimer) {
                    var isAutoRefresh = true;
                    this.refresh(isAutoRefresh);
                } 

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

                    this.autoRefresh.toid = setTimeout(
                        function () { that._refresh(); },
                        this.autoRefresh.every
                    );
                }
            },
            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._refresh(); },
                            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;
            },

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

    });

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

        Screen.Models.Recipes = Backbone.Epoxy.Model.extend({
            defaults: {
                errorMsg: '',
                processing: true,
                title: '',
                hasData: false,
                isLoading: true,
                index: null,

                selectedMaterialId: null,
                selectedMaterialName: null,
                show_unassign_btn: false,
            },
            initialize: function () {
                this.recipes = new Screen.Collections.ItemsColl();
            },

            getMaterialRecipes: function (params) {
                var that = this;
                var qp = new Core.Database.QueryParameters();
                qp.Add('@MaterialId', 'INT', params.MaterialId);
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.SCRAP.GetRecipesByMaterialId',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {

                                if (resp && resp.Table) {

                                    that.recipes.setDataColl(resp.Table);

                                }
                                else {
                                    if ((resp) && (resp.Message)) {

                                    }
                                    else {
                                    }

                                }


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

                return this;

            },
        });


        Screen.Views.RecipesModal = Backbone.Epoxy.View.extend({
            template: "materials-commodities",
            id: "materials-recipes",
            className: "modal modal-material-recipes hide fade",
            bindings: "data-bind",
            isCacheable: true,
            events: function () {
                return {
                    "click #acceptBtn": this.acceptBtn_click,
                    "click #cancelBtn": this.cancelBtn_click,
                    "submit form": this.form_submit,
                    "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,
            row: [],
            recipes: [],
            grid: [],
            initialize: function (options) {
                _.extend(this, options);
                if (!this.model) {
                    this.model = new Screen.Models.Recipes();
                }
                this.row = options.row;
                this.model.set({
                    selectedMaterialId: this.row.get('Id'),
                    selectedMaterialName: this.row.get('Name'),
                    title: " Disabling material " + this.row.get('Name'),
                });

                this.model.getMaterialRecipes({ MaterialId: this.model.get('selectedMaterialId') });
                

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

                        var columns = [
                            {
                                name: 'Name',
                                label: 'Recipes Affected',
                                cell: Backgrid.StringCell.extend({
                                    className: 'string-cell align-center-cell',
                                }),
                                editable: false,
                                sortable: false,
                            }

                        ];
                        var grid = new Backgrid.Grid({
                            className: 'backgrid table table-hover table-condensed',
                            collection: that.model.recipes,
                            columns: columns,
                            row: Backgrid.Row.extend({
                                initialize: function (options) {
                                    Backgrid.Row.prototype.initialize.apply(this, arguments);

                                }
                            }),
                        });

                        that.grid = grid;
                        that.$el.find('.material-recipes-container').append(grid.render().el);

                        that.isRendered = true;


                        that.trigger("recipesReady");
                        that.trigger("render");


                    }, true, customPath);

                }, customPath, "disallow_materials_modal");

            },
            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);
                this.listenToOnce(this, 'recipesReady', this.recipes_ready);

            },

            recipes_ready: function () {
                try {
                    var that = this;
                    setTimeout(
                        function () {
                            that.model.set({
                                hasData: (that.model.recipes.length > 0),
                                processing: false,
                                isLoading: false,
                            });
                        },
                        100
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            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 () {
            },

            acceptBtn_click: function (e) {
                try {
                    this.bus.trigger("modalAcceptBtn", this.model.get('selectedMaterialName'));

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

            cancelBtn_click: function (e) {
                try {
                    this.bus.trigger("modalCancelBtn");

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

            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.show();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },

        });


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