//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',
  'js/jquery.clearsearch/jquery.clearsearch',
],

function (app, T, Backgrid, Modal) {

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


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



    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {
            items: null,

            hasData: true,
            isLoading: false,

            fluxMaterials: [],

        },

        initialize: function () {
            this.attributes.items = new Screen.Collections.Items();
            this.fetch();
        },
        fetch: function () {
            var that = this,
                qp = new Core.Database.QueryParameters();

            var array = [];
            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.MES.GetSilosConfiguration',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                that.set({
                                    fluxMaterials: resp.Table1,
                                })
                                that.attributes.items.setDataColl(resp.Table);
                            }
                            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); }
                    },
                    Async: false,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );

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

            console.log("update", params);

            qp.Add('@MaterialId', 'INT', parseInt(params.Id));
            qp.Add('@FurnaceCode', 'INT', parseInt(params.FurnaceCode));
            qp.Add('@SiloCode', 'INT', parseInt(params.SiloCode));

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.MES.UpdateSilosConfiguration',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && !(resp.Message)) {
                                app.views.topMessages.showMessage('Material updated', { stay: 5000, });
                            }
                            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); }
                    },
                    Async: false,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );
        },
     
      
    });

    //the generate id method is called everytime a view is going to be shown by the router and returns and id that
    //is used by the router to store in cache (if it is cacheable) and to know the current shown view.
    //this is useful in case your view is reusable, and displays different data depending on url parameters 
    //(such as a catalog view, or a report that doesnt change in terms of UI but it does change in terms of data)
    //so you can always use the same view on the router but the cache can tell which view is which by using differents ids.
    Screen.generateID = function (viewParams) {
        try {
            //if the viewparams change the view id, then evaluate the viewparams here
            //and return the appropiate id.
            return 'silos-configuration';
        } catch (Error) { }
    }

    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: 'silos-configuration',
        id: 'silos-configuration',
        title: 'Silos Configuration',
        //default not cacheable, change this if you want the view to be cacheable
        // if the view is set as cacheable should also have a refresh method to reset the view without erasing the DOM.
        isCacheable: false,
        events: function () {
            return {
            };
        },
        autoRefresh: null,
        subviews: null,
        viewParams: null,

        item: null,
        //specsColl: null,

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

            var that = this;

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

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

            var array = [];
            this.fluxMaterials = [];
            _.each(this.model.get('fluxMaterials'), function (obj, i) {
                array[i] = [obj.Name, obj.Id];
            });
            this.fluxMaterials = array;

            this.subviews = {
                subnavbarControls: new Screen.Views.SubnavBarControls({
                    model: this.model,
                    bindingSources: this.bindingSources,
                    parent: this,
                    container: app.views.subnavbar.getSectionContainer(1, 12),
                    events: function () {
                        return {
                            'click #refreshBtn': _.bind(that.refreshBtn_click, that),
                        };
                    },
                }),
            };


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

            this.viewParams = viewParams;

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

            //the screens have a custompath, so it has to be specified in the customPath variable that is
            //then sent to the template loader.
            var customPath = '/app/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) {
                            //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.subviews.subnavbarControls.render();

                            var grid = that.options.itemsGrid = new Backgrid.Grid({
                                className: 'backgrid table table-hover',
                                columns: [
                                    {
                                        name: 'Furnace',
                                        label:'Furnace',
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.StringCell.extend({
                                            orderSeparator: '',
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },
                                    {
                                        name: 'SiloCode',
                                        label: 'Silo',
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.StringCell.extend({
                                            orderSeparator: '',
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },
                                    {
                                        name: 'Id',
                                        label: 'Material',
                                        editable: true,
                                        sortable: false,
                                        cell: Backgrid.SelectCell.extend({
                                            optionValues: function () {
                                                return that.fluxMaterials;
                                            },
                                            className: 'string-cell align-center-cell',
                                        }) 
                                    },                                    
                                ],
                                collection: that.model.get('items'),
                            });
                            that.$el.find('.items-grid-container').append(grid.render().el);

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


                        },
                        true,
                        customPath
                    );
                },
                customPath
            );
        },

        refreshBtn_click: function () {
            this.model.set({
                hasData: false,
                isLoading: true,
            });

            this.model.fetch();
            //this._refresh();
        },
        bindEvents: function () {
            this.listenTo(this.model.get('items'), 'change', this.collection_changed)
                .listenTo(this.model.get('items'), 'fetch', this.collection_fetch);
        },
      

        collection_changed: function (m, b, c) {
            var that = this;
            var fromFetch = (b && b.from == 'fetch') ? true : false;

            if (!fromFetch) {
                console.log("entra", m);
                this.model.update({
                    FurnaceCode: m.get('FurnaceCode')
                    , SiloCode: m.get('SiloCode')
                    , Id: m.get('Id')
                })
                //m.collection.upsertItem(m.get('id'), [
                //{ name: 'id', type: 'INT', value: m.get('id') },
                //{ name: 'active', type: 'BIT', value: m.get('active') },
                //{ name: 'name', type: 'VARCHAR', value: m.get('name') },
                //{ name: 'smartId', type: 'INT', value: Number(m.get('smartId')) == 0 ? null : Number(m.get('smartId')) },
                //], function (ref, ids) {
                //}, function (coll, msg) {
                //    app.views.topMessages.showMessage(app.translate(app, msg), { stay: 10000, });
                //    that._refresh();
                //});
            }
        },
        collection_fetch: function (coll, resp) {
            try {
                var array = [];
                this.fluxMaterials = [];
                _.each(this.model.get('fluxMaterials'), function (obj, i) {
                    array[i] = [obj.Name, obj.Id];
                });
                this.fluxMaterials = array;

                this.model.set({
                    hasData: (this.model.get('items').length > 0),
                    isLoading: false,
                });

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


        //Common functions

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

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

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

                this.options.onappend(this);
            }

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

            if (this.options.state == app.view_states.closed) {
                //return without appending.
                return;
            }
        },
       
        stopAutoRefresh: function () {
            if (this.autoRefresh.toid != null) {
                clearTimeout(this.autoRefresh.toid);
                this.autoRefresh.toid = null;
            }
            this.autoRefresh.enabled = false;
        },
        bindViewScopedEvents: function () {
        },
        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.stopAutoRefresh();

            this.$el.hide();
            this.unbind();
            this.stopListening();
        },
        hideSubviews: function () {
            _.each(this.subviews, function (sview) {
                sview.hide();
            });
        },
        preRender: function () {
            app.models.subnavbar.setAll(false);
            app.models.subnavbar.set('sections', '12');
            app.models.subnavbar.set('subnavbar', true);
        },
        reRender: function () {
            this.startAutoRefresh();
        },
             
       
   
     
      
    });

    //subview for the subnavbar controls
    Screen.Views.SubnavBarControls = Backbone.Epoxy.View.extend({
        id: 'silos-configuration-subnavbar-controls',
        title: '',
        template: 'silos-configuration',

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

            this.bindEvents();
        },
        render: function (container, onComplete) {
            var that = this;
            var thatContainer = (container) ? container : (this.options.container) ? this.options.container : null;
            var onViewComplete = (onComplete) ? onComplete : function () { };

            //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/custom-screens/silos-configuration/';

            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;

                    var ctx = {
                        editable: (($.inArray('AdminUserRole', app.models.user.get('roles')) != -1
                            || $.inArray('SupervisorUserRole', app.models.user.get('roles')) != -1) ? true : false),
                    };

                    //loading the view and appeding it to the views's $el.
                    that.$el.html(tmp(
                        _.extend({}, ctx, (that.model) ? that.model.toJSON() : {})
                    ));

                    that.applyBindings();

                    that.append(thatContainer, that.$el);

                }, true, customPath);
            }, customPath, 'subnavbar_controls');

        },
        bindEvents: function () {
            //this function should be in every view that uses listenTo anywhere
            //all the model bindings or view-model binding should be here, to manage
            //the show/hide view easily
        },

        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;
            }
        },
        close: function () {
            this.options.state = app.view_states.closed;

            this.remove();
            this.unbind();
        },
        show: function () {
            this.options.state = app.view_states.shown;

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

            this.$el.hide();
            this.unbind();
            this.stopListening();
        },
    });

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

});
