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

  //'backgrid/infinator',
],

function (app, T, Backgrid, Modal) {

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

    Screen.Models.Item = Backbone.Epoxy.Model.extend({
        defaults: {
            carbonPrice: null,
            energyPrice: null,
            limePrice: null,
            naturalGasPrice: null,
            oxygenPrice: null,
        },

        parse: function (objs) {
            var result = {};

            if (objs) {
                var obj = objs[0];

                result = {
                    id: obj.ProductTypeId, //Add an id attribute to prevent refresh input data when user is editing and collection refreshes itself.
                };

                _.each(objs, function (obj) {
                    switch (obj.Code.toUpperCase()) {
                        case 'CARBON':
                            result.carbonPrice = obj.Price;
                            break;
                        case 'ENERGY':
                            result.energyPrice = obj.Price;
                            break;
                        case 'LIME':
                            result.limePrice = obj.Price;
                            break;
                        case 'NATURAL_GAS':
                            result.naturalGasPrice = obj.Price;
                            break;
                        case 'OXYGEN':
                            result.oxygenPrice = obj.Price;
                            break;
                        default:
                            break;
                    }
                });
            }

            return result;
        },
    });

    Screen.Collections.Items = Backbone.Collection.extend({
        model: Screen.Models.Item,

        fixedParameters: [],
        isFetching: false,
        currentPage: 1,
        pageSize: 50,
        transaction_timestamp: null,

        fetch: function (opt) {
            var that = this,
                qp = new Core.Database.QueryParameters(),
                ttimestamp = this.transaction_timestamp = new Date().getTime(),
                options = opt ? _.clone(opt) : {};

            qp.Add('@onlyActives', 'BIT', false);

            if (options.reset) {
                this.resetPagination(true);

                this.fixedParameters = [];
            }

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

            if (options.refresh) {
                qp.Add('@fromRow', 'INT', 0);
                qp.Add('@rowsToFetch', 'INT', this.currentPage * this.pageSize);
            }
            else if (options.reset) {
                qp.Add('@fromRow', 'INT', 0);
                qp.Add('@rowsToFetch', 'INT', this.pageSize);
            }
            else {
                qp.Add('@fromRow', 'INT', (this.currentPage - 1) * this.pageSize);
                qp.Add('@rowsToFetch', 'INT', this.pageSize);
            }


            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.CAT.GetConsumables',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            //checking transaction timestamp
                            if (ttimestamp != that.transaction_timestamp)
                                return;

                            if ((resp) && (resp.Table)) {
                                var records = resp.Table,
                                    newColl;

                                newColl = that.model.prototype.parse(records);

                                var method = ((options.refresh) || ((options.reset))) ? 'set' : 'add';

                                //checking transaction timestamp
                                if (ttimestamp != that.transaction_timestamp)
                                    return;

                                var editingItems = _.where(that.toJSON(), { isNew: true });
                                [].push.apply(newColl, editingItems);

                                that[method](newColl, { from: 'fetch' })
                                    .trigger('fetch', that, records);

                                //decreasing page since we couldn't get any data on this page.
                                if (newColl.length == 0 && method == 'add')
                                    that.currentPage--;

                                that.isFetching = false;
                            }
                            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: options.async,
                    Secured: 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);
            }
        },
    });

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

            hasData: false,
            isLoading: true,
        },
        computeds: {
        },

        initialize: function () {
            this.attributes.items = new Screen.Collections.Items();
        },
    });

    //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 'consumables';
        } catch (Error) { }
    }

    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: 'consumables',
        id: 'consumables',
        title: 'Consumables',
        //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,

        minMaxEafItemColl: 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: 15 * 1000
            };

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


            this.subviews = {
                subnavbarControls: new Screen.Views.SubnavBarControls({
                    model: this.model,
                    parent: this,
                    container: app.views.subnavbar.getSectionContainer(1, 12),
                    events: function () {
                        return {
                            //'click .add-item': _.bind(that.addNewBtn_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: 'energyPrice',
                                        label: app.translate(that, 'energy_price_col'),
                                        editable: true,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell align-center-cell',
                                            decimals: 4,
                                        }),
                                    },
                                    {
                                        name: 'oxygenPrice',
                                        label: app.translate(that, 'oxygen_price_col'),
                                        editable: true,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell align-center-cell',
                                            decimals: 4,
                                        }),
                                    },
                                    {
                                        name: 'naturalGasPrice',
                                        label: app.translate(that, 'natural_gas_price_col'),
                                        editable: true,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell align-center-cell',
                                            decimals: 4,
                                        }),
                                    },
                                    {
                                        name: 'carbonPrice',
                                        label: app.translate(that, 'carbon_price_col'),
                                        editable: true,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell align-center-cell',
                                            decimals: 4,
                                        }),
                                    },
                                    {
                                        name: 'limePrice',
                                        label: app.translate(that, 'lime_price_col'),
                                        editable: true,
                                        sortable: false,
                                        cell: Backgrid.NumberCell.extend({
                                            className: 'number-cell align-center-cell',
                                            decimals: 4,
                                        }),
                                    },
                                ],
                                collection: that.model.get('items'),
                            });
                            that.$el.find('.items-grid-container').append(grid.render().el);

                            //end

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

                            //Call first refresh.
                            that.startAutoRefresh();
                        },
                        true,
                        customPath
                    );
                },
                customPath
            );
        },
        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
            this.listenTo(this.model.get('items'), 'change', this.collection_changed)
                //.listenTo(this.model.get('items'), 'add remove', this.collectionAddRemove)
                .listenTo(this.model.get('items'), 'fetch', this.collection_fetch)
        },

        _refresh: function (opt) {
            //console.log('autorefresh: ' + new Date().toString()); 
            if (this.autoRefresh.toid != null) {
                clearTimeout(this.autoRefresh.toid);
                this.autoRefresh.toid = null;
            }

            this.refreshItemsColl(opt);

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

                this.autoRefresh.toid = setTimeout(
                    function () { that._refresh(); },
                    this.autoRefresh.every
                );
            }
        },
        refresh: function (viewParams) {
            //if (viewParams.sectionParam1)
            //    viewParams.sectionParam1 = parseInt(viewParams.sectionParam1, 10);
            //else
            //    viewParams.sectionParam1 = Screen.Models.Main.prototype.defaults.recipeId;

            //this.model.set({
            //    recipeId: viewParams.sectionParam1,
            //});
        },
        refreshItemsColl: function (options) {
            var that = this,
                itemsColl = this.model.get('items'),
                opt = _.extend({}, options, { params: {}, refresh: true, });

            if (opt.reset == true)
                this.model.set('isLoading', true);

            var that = this,
                modelAttrs = this.model.toJSON();

            itemsColl.fetch(_.extend(
                opt,
                {
                    params: _.extend(
                        modelAttrs,
                        opt.params,
                        {
                            refresh: opt.refresh,
                            reset: opt.reset,
                        }
                    ),
                }
            ));
        },

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

        updateVariables: function (itemsChanged, success, error) {
            var that = this;
            var QP = new QueryParameters();
            var items = [];

            for (var prop in itemsChanged) {
                switch (prop) {
                    case 'carbonPrice':
                        items.push({ code: 'CARBON', price: itemsChanged[prop], });
                        break;
                    case 'energyPrice':
                        items.push({ code: 'ENERGY', price: itemsChanged[prop], });
                        break;
                    case 'limePrice':
                        items.push({ code: 'LIME', price: itemsChanged[prop], });
                        break;
                    case 'naturalGasPrice':
                        items.push({ code: 'NATURAL_GAS', price: itemsChanged[prop], });
                        break;
                    case 'oxygenPrice':
                        items.push({ code: 'OXYGEN', price: itemsChanged[prop], });
                        break;
                    default:
                        break;
                }
            }

            QP.Add(
                'items',
                'XML',
                app.jsonArrayToXml(
                    items,
                    [
                        'code',
                        'price',
                    ]
                )
            );

            Core.Json.CallProcedure(app.DatabaseNames.MES + '.CAT.UpsertConsumable', QP, {
                onSuccess: function (data) {
                    if (data && data.Table && data.Table.length > 0) {
                        var data = data.Table;

                        if (!data[0].Message) {
                            if (success != null && _.isFunction(success))
                                success.call(this, that);
                        }
                        else {
                            error.call(this, that, data[0].Message);
                        }
                    } else {
                        if (data.Message)
                            error.call(this, that, data.Message);
                        else
                            error.call(this, that);
                    }
                },
                onError: function (data) {
                    if (error != null && _.isFunction(error))
                        error.call(this, that);
                },
                Async: true,
                Secured: true,
            }, app.ConnectionStrings.app);
        },

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

            if (!fromFetch && !avoidSync) {
                this.updateVariables(
                    m.changed,
                    function (ref, ids) {},
                    function (coll, msg) {
                        app.views.topMessages.showMessage(app.translate(app, msg), { stay: 10000, });
                        that._refresh();
                    }
                );
            }
        },
        collection_fetch: function (coll, resp) {
            try {
                this.model.set({
                    hasData: (this.model.get('items').length > 0),
                    isLoading: false,
                });
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
    });

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

        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/consumables/';

            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;

});
