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

  "modules/modal",

  "bootstrap/colorpicker",
],

function (app, T, Modal) {

    //replace all "Products" with your view's name.
    var Products = { Models: {}, Views: {}, Collections: {} }

    Products.Models.Item = Backbone.Model.extend({
        defaults: {
            id: null,
            code: null, 
            name: null,
            enabled: true, 
        }, 
    });

    Products.Collections.Items = Backbone.Collection.extend({
        model: Products.Models.Item,
        initialize: function () {
            _.bindAll(this);
        },
        fetch: function (opt) {
            var options = {
                method: "set",
                async: true,
                callback: null,
            };

            options = _.extend(options, (opt) ? opt : {});

            var that = this,
                QP = new Core.Database.QueryParameters();

            var items = [];

            Core.Json.CallProcedure(app.DatabaseNames.OEE + ".WebApp.GetProductsCatalog", QP, {
                onSuccess: function (data) {
                    if (Core.Object.Eval(data, "Table")) {
                        var data = data.Table;

                        for (var i = 0; i < data.length; i++) {
                            var itemData = data[i];

                            items.push({
                                id: itemData.Id,
                                code: itemData.Code, 
                                name: itemData.Name,
                                enabled: itemData.Enabled, 
                            });
                        }
                    }

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

                    that[options.method](items, { from: "fetch" });

                    if (options.callback != null && _.isFunction(options.callback))
                        options.callback.call(this, that);
                },
                Async: options.async,
                Secured: true,
            }, app.ConnectionStrings.app);

            return this;
        },
        upsertItem: function (id, props, success, error) {
            var that = this;
            var QP = new QueryParameters();

            QP.Add("Id", "INT", id);

            for (var q in props) {
                QP.Add(props[q].name, props[q].type, props[q].value);
            }

            Core.Json.CallProcedure(app.DatabaseNames.OEE + ".WebApp.UpsertProduct", QP, {
                onSuccess: function (data) {
                    if (data && data.Table) {
                        var data = data.Table;
                        var ids = _.pluck(data, 'Id');

                        if (success != null && _.isFunction(success))
                            success.call(this, that, ids);
                    } else {
                        if (error != null && _.isFunction(error))
                            error.call(this, that);
                    }
                },
                onError: function (data) {
                    if (error != null && _.isFunction(error))
                        error.call(this, that);
                },
                Async: true,
                Secured: true,
            }, app.ConnectionStrings.app);
        },
        callRemoveItem: function (id, success, error) {
            var that = this;
            var QP = new QueryParameters();

            QP.Add("@Id", "INT", id);

            Core.Json.CallProcedure(app.DatabaseNames.OEE + ".WebApp.RemoveProduct", QP, {
                onSuccess: function (data) {
                    if (data && data.Table && data.Table[0].Status == 1) {
                        var data = data.Table1;
                        var ids = _.pluck(data, 'Id');

                        if (success != null && _.isFunction(success))
                            success.call(this, that, ids);
                    } else {
                        error.call(this, that
                            , (data && data.Table && data.Table[0]) ? 
                            data.Table[0] : {}
                        );
                    }
                },
                Async: true,
                Secured: true,
            }, app.ConnectionStrings.app);
        },
        removeItem: function (id, success, error) {
            var that = this;
            var model = this.get(id);
            if (model) {
                this.callRemoveItem(
                    id
                    , function (ref, ids) {
                        //removing from collection; 
                        that.remove(model);

                        if (success && _.isFunction(success))
                            success.call(this, that, ids);
                    },
                    function (ref, data) {
                        if (error && _.isFunction(error))
                            error.call(this, that, data);
                    }
                );
            }
        },
        setItemEnabled: function (id, success, error) {
            var that = this;
            var QP = new QueryParameters();

            QP.Add("@Id", "INT", id);
            QP.Add("@Enabled", "BIT", 1);

            Core.Json.CallProcedure(app.DatabaseNames.OEE + ".WebApp.SetProductEnabled", QP, {
                onSuccess: function (data) {
                    if (data && data.Table) {
                        var data = data.Table;
                        var ids = _.pluck(data, 'Id');

                        if (success != null && _.isFunction(success))
                            success.call(this, that, ids);
                    } else {
                        error.call(this, that);
                    }
                },
                Async: true,
                Secured: true,
            }, app.ConnectionStrings.app);
        }
    }); 

    Products.Models.Main = Backbone.Model.extend({
        defaults: {
            items: null, 
        },
        initialize: function () {
            this.attributes.items = new Products.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.
    Products.generateID = function (viewParams) {
        try {
            //if the viewparams change the view id, then evaluate the viewparams here
            //and return the appropiate id.
            return "products"; 
        } catch (Error) { }
    }

    Products.Views.Main = Backbone.View.extend({
        template: "products"
        , id: "products"
        , title: "Products"
        //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: true
        , initialize: function () {
            this.options.state = app.view_states.loading;
            this.options.onappend = (_.isFunction(this.options.onappend)) ? this.options.onappend : function () { };

            if (this.options.viewParams) {
            }

            var model = new Products.Models.Main({                
            });

            this.model = model;

            this.options.MYREFERENCES = {
                subviews: {
                }
                , autoRefresh: {
                    enabled: true
                    , toid: null
                }
            };

            this.bindEvents();
            _.bindAll(this);
        },

        events: {
        }, 

        render: function (container) {
            var that = this;
            var thatContainer = (container != null && container != undefined) ? container : this.options.container;

            //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.oeeModule.screensPath + "OEEConfiguration/products/";

            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;
                    //start: before the view is visible, but the template was already loaded (not instanced nor appended)

                    //end:

                    //loading the view and appeding it to the views's $el.
                    that.$el.html(tmp());

                    that.options.MYREFERENCES.subviews.subnavbarControls = new Products.Views.SubnavBarControls({
                        parent: that
                        , container: app.views.subnavbar.getSectionContainer(1, 12)
                        , events: {
                            "click .add-item": that.addNew,
                        }
                    });

                    //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")

                    var ActionsCell = Backgrid.Cell.extend({
                        template: Handlebars.compile(that.$el.find("#actions_cell_template").html()),
                        className: "actions-cell", 
                        initialize: function () {
                            Backgrid.Cell.prototype.initialize.apply(this, arguments);
                            this.bindEvents();
                        },
                        events: {
                            "click .btn-cell-action": "cellActionClick"
                        },
                        cellActionClick: function (e) {
                            var target = $(e.target);
                            var actionData = target.closest("[data-cell-action]").data("cell-action");
                            if (actionData) {
                                that.actionOnRow(this.model, actionData);
                            }
                        },
                        render: function () {
                            var mode = "ENABLED"; 

                            if (this.model.get("isNew"))
                                mode = "NEW";
                            else if (!this.model.get("enabled"))
                                mode = "DISABLED"; 

                            this.$el.html(this.template({
                                mode: mode, 
                            }));

                            this.$el.find("[data-toggle='tooltip']").tooltip();

                            this.checkMode();
                            this.delegateEvents();
                            return this;
                        },
                        setNewRowMode: function(val){
                            var btnRemove = this.$el.find(".btn-remove");
                            var btnSave = this.$el.find(".btn-save");
                            var btnDiscard = this.$el.find(".btn-discard");

                            if (val) {
                                btnRemove.addClass("hide");
                                btnSave.removeClass("hide");
                                btnDiscard.removeClass("hide");
                            } else {
                                btnRemove.removeClass("hide");
                                btnSave.addClass("hide");
                                btnDiscard.addClass("hide");
                            }
                        },
                        checkMode: function () {
                            //var newRow = this.model.get("isNew");
                            //if (newRow) this.setNewRowMode(true);
                            //else this.setNewRowMode(false); 
                        }, 
                        bindEvents: function () {
                            this.listenTo(this.model, "change:isNew", this.render); 
                        },
                    });

                    var columns = [
                        {
                            name: "code",
                            label: app.translate(that, "code_label"),
                            editable: true,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell name",
                            })
                        },
                        {
                            name: "name",
                            label: app.translate(that, "name_label"),
                            editable: true,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell name",
                            })
                        },
                        {
                            name: "actions",
                            label: "",
                            editable: false,
                            sortable: false,
                            cell: ActionsCell
                        },
                    ];

                    var CustomRow = Backgrid.Row.extend({
                        initialize: function () {
                            Backgrid.Row.prototype.initialize.apply(this, arguments);

                            this.bindEvents();
                        },
                        render: function () {
                            Backgrid.Row.prototype.render.apply(this, arguments);

                            if (!this.model.get("enabled")) {
                                this.$el.addClass("disabled-row");
                            } else {
                                this.$el.removeClass("disabled-row");
                            }

                            return this;
                        },
                        bindEvents: function () {
                            this.listenTo(this.model, "change:enabled", this.render);
                        },
                    });

                    var grid = that.options.itemsGrid = new Backgrid.Grid({
                        className: "backgrid table table-hover",
                        columns: columns,
                        row: CustomRow, 
                        collection: that.model.get("items"),
                    });

                    that.$el.find(".items-grid-container").append(grid.render().el);
                    that.options.MYREFERENCES.subviews.subnavbarControls.render();

                    //end

                    //appending view to the main container
                    that.append(thatContainer, that.$el); 
                    that._startAutoRefresh(); 
                }, true, customPath);
            }, customPath, "main_template");
        }

        , 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.options.MYREFERENCES.autoRefresh.toid != null) {
                    clearTimeout(this.options.MYREFERENCES.autoRefresh.toid);
                    this.options.MYREFERENCES.autoRefresh.toid = null;
                }

                this.options.MYREFERENCES.autoRefresh.enabled = true;

                this._autoRefresh();
            } catch (Error) { }
        }

        , _autoRefresh: function () {
            if (this.options.MYREFERENCES.autoRefresh.toid != null) {
                clearTimeout(this.options.MYREFERENCES.autoRefresh.toid);
                this.options.MYREFERENCES.autoRefresh.toid = null;
            }

            this.refresh();

            if (this.options.MYREFERENCES.autoRefresh.enabled == true) {
                this.options.MYREFERENCES.autoRefresh.toid = setTimeout(this._autoRefresh, 5000);
            }
        }

        , _stopAutoRefresh: function () {
            if (this.options.MYREFERENCES.autoRefresh.toid != null) {
                clearTimeout(this.options.MYREFERENCES.autoRefresh.toid);
                this.options.MYREFERENCES.autoRefresh.toid = null;
            }
            this.options.MYREFERENCES.autoRefresh.enabled = false;
        }

        , refresh: function () {
            try {
                this.model.get("items").fetch(); 
            } catch (Error) { }
        }

        , collectionChanged: function (m, b, c) {
            var that = this; 
            var fromFetch = (b && b.from == "fetch") ? true : false;
            var avoidSync = (b && b.avoidSync) ? b.avoidSync : false; 
            var isNewRow = m.get("isNew");

            if (!fromFetch && !isNewRow && !avoidSync) {
                m.collection.upsertItem(m.get("id"), [
                    { name: "Code", type: "VARCHAR", value: m.get("code") },
                    { name: "Name", type: "VARCHAR", value: m.get("name") },
                ], function (ref, ids) {
                }, function (ref, ids) {
                    that.refresh(); 
                }); 
            }
        }

        , actionOnRow: function (model, action) {
            switch (action.toUpperCase()) {
                case "DELETE":
                    this.removeRow(model); 
                    break;
                case "SAVE":
                    this.saveRow(model); 
                    break;
                case "DISCARD":
                    this.discardRow(model); 
                    break;
                case "ENABLE":
                    this.enableRow(model); 
                    break; 
            }
        }

        , removeRow: function (model) {
            var that = this; 
            model.collection.removeItem(
                model.get("id")
                , function (data) {
                    that.refresh(); 
                }
                , function (ref, data) {
                    if (data && data.Message) {
                        app.views.topMessages.showMessage(app.translate(that, "product_with_batch_open_or_new"));
                    }

                    that.refresh();
                }
            );
        }

        , enableRow: function (model) {
            var that = this;
            model.collection.setItemEnabled(
                model.get("id")
                , function (data) {
                    that.refresh();
                }
                , function (data) {
                    that.refresh();
                }
            );
        }

        , saveRow: function (m) {
            var that = this; 
            m.collection.upsertItem(null, [
                { name: "Code", type: "VARCHAR", value: m.get("code") },
                { name: "Name", type: "VARCHAR", value: m.get("name") },
            ], function (ref, ids) {
                m.set({ id: ids[0], isNew: false }, { avoidSync:true });
                that.refresh(); 
            }, function (ref, ids) {
                that.refresh(); 
            }); 
        }

        , discardRow: function (m) {
            //to discard just remove the model from the collection.
            m.collection.remove(m);
        }

        , addNew: function () {
            this.model.get("items").unshift({
                id: -1,
                isNew: true, 
            }); 
        }

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

        , bindViewScopedEvents: function () {
        }

        , unbindViewScopedEvents: function () {
        }

        , close: function () {
            this.options.state = app.view_states.closed;

            this.closeSubviews();
            this.remove();
            this.unbindViewScopedEvents();
            this.unbind();
        }

        , closeSubviews: function () {
            _.each(this.options.MYREFERENCES.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.options.MYREFERENCES.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.options.MYREFERENCES.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
    Products.Views.SubnavBarControls = Backbone.Epoxy.View.extend({
        id: "products-subnavbar-controls"
        , title: ""
        , template: "products"
        , initialize: function () {
            this.options.state = app.view_states.loading;
            this.options.onappend = (_.isFunction(this.options.onappend)) ? this.options.onappend : function () { };

            if (this.options.viewParams) {
            }

            this.options.MYREFERENCES = {};

            //this.model = (this.model) ? this.model : new Products.Models.SubnavBarControls();

            this.bindEvents();
            //_.bindAll(this);
        },

        events: {
        },

        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.oeeModule.screensPath + "OEEConfiguration/products/";

            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");

        }

        , 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;
            }
        }
        , refresh: function () {
            try {

            } catch (Error) { }
        }

        , 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
        }

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

        , reRender: function () {
        }
    });

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

});
