/// <reference path="http://localhost:65492/IndustrialDashboard/Scripts/IndustrialDashboard-debug.js" />
//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",

  "backgrid",

  "moment",

  "oee-module-screens/delays/delay-information-modal/delay-information-modal",
],

function (app, T, Modal, Backgrid, moment, DelayInformationModal) {

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

    DelaysSimple.Models.Main = Backbone.Model.extend({
        defaults: {
            delaySplits: null, 
        }
    });

    //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.
    DelaysSimple.generateID = function (viewParams) {
        try {
            //if the viewparams change the view id, then evaluate the viewparams here
            //and return the appropiate id.
            return "delays-simple"; 
        } catch (Error) { }
    }

    DelaysSimple.Models.DelaySplit = Backbone.Model.extend({
        defaults: {
            delayId: null,
            parentId: null,
            line: null,
            productionItem: null, 
            start: null,
            end: null,
            duration: null,
            seconds: null, 
            delayCodeId: null,
            code: null, 
            comments: null,
            batchNumber: null, 
        }, 
    });

    DelaysSimple.Collections.DelaySplits = Backbone.Collection.extend({
        model: DelaysSimple.Models.DelaySplit,
        initialize: function () {
        },
        comparator: function (a, b) {
            var prodItemA = a.get("productionItem");
            var prodItemB = b.get("productionItem");
            var startA = a.get("start");
            var startB = b.get("start");

            if (prodItemA == prodItemB) {
                if (startA > startB) return -1;
                else if (startA < startB) return 1;
                else return 0; 
            } else {
                if (prodItemA > prodItemB) return -1;
                else return 1; 
            }
        }, 
        fetch: function (e) {
            var that = this;
            var QP = new Core.Database.QueryParameters();

            var data = (e.data) ? e.data : {};

            QP.Add("ProductionItemId", "INT", data["productionItemId"]);
            QP.Add("Timezone", "VARCHAR", data["timezone"] ? data["timezone"] : null);

            Core.Json.CallProcedure(app.DatabaseNames.OEE + ".WebApp.GetLastDelays", QP, {
                onSuccess: function (data) {
                    if (data && data.Table) {
                        data = data.Table;

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

                            var delaySplit = data[i];
                            var delaySplitModel = new DelaysSimple.Models.DelaySplit({
                                id: delaySplit.Id,
                                delayId: delaySplit.Id,
                                parentId: delaySplit.ParentId,
                                line: delaySplit.Line,
                                productionItem: delaySplit.ProductionItem, 
                                start: new moment(delaySplit.Start).format("YYYY-MM-DD HH:mm:ss"),
                                end: (delaySplit.End)
                                        ? new moment(delaySplit.End).format("YYYY-MM-DD HH:mm")
                                        : null,
                                duration: delaySplit.Duration,
                                seconds: delaySplit.Seconds,
                                code: delaySplit.Code,
                                comments: delaySplit.Comments,
                                batchNumber: delaySplit.BatchNumber, 
                            });

                            delaySplitsModels.push(delaySplitModel);
                        }

                        that.set(delaySplitsModels, { from: "fetch" });

                        if (e && e.callback && _.isFunction(e.callback))
                            e.callback.call(that, that, data);

                    }
                },
                onError: function(){
                    if (e && e.callback && _.isFunction(e.callback))
                        e.callback.call(that, that, "error");
                }, 
                Secured: true,
                Cache: true, 
            }, app.ConnectionStrings.app);
        },
    });

    DelaysSimple.Views.Main = Backbone.View.extend({
        template: "delays-simple"
        , id: "delays-simple"
        , title: "DelaysSimple"
        //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
        , 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 DelaysSimple.Models.Main({
                delaySplits: new DelaysSimple.Collections.DelaySplits(), 
            });

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

            this.model = model;

            this.options.MYREFERENCES.subviews.subnavbarControls = new DelaysSimple.Views.SubnavBarControls({
                parent: this
                , model: new DelaysSimple.Models.SubnavBarControls()
                , container: app.views.subnavbar.getSectionContainer(1, 12)
            });

            this.options.MYREFERENCES.subviews.subnavbarControls.render();

            this.options.demouser = $.inArray("DemoUserRole", app.models.user.get("roles")) != -1;

            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 + "delays/delays-simple/";

            T.render.call(this, this.template, function (tmp) {
                //getInternationalizationData
                if (!that.options.i18n) that.options.i18n = {};
                app.getI18NJed(that, that.template, function (i18nJED) {
                    //storing internationalization data
                    that.options.i18n[that.template] = i18nJED;
                    that.$el.html(tmp());

                    var columns = [
                        {
                            name: "line",
                            label: app.translate(that, "line_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                            })
                        },
                        {
                            name: "productionItem",
                            label: app.translate(that, "machine_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                            })
                        },
                        {
                            name: "start",
                            label: app.translate(that, "start_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                            })
                        },
                        {
                            name: "end",
                            label: app.translate(that, "end_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                                render: function () {
                                    Backgrid.StringCell.prototype.render.apply(this, arguments);
                                    if (this.model.get("end") == null) {
                                        this.$el.text("...");
                                    }
                                    return this;
                                },
                            })
                        },
                        {
                            name: "duration",
                            label: app.translate(that, "duration_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                                render: function () {
                                    Backgrid.StringCell.prototype.render.apply(this, arguments);
                                    if (this.model.get("duration") == null) {
                                        this.$el.text("...");
                                    }
                                    return this;
                                },
                            })
                        },
                        {
                            name: "batchNumber",
                            label: app.translate(that, "batchNumber_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                            })
                        }, 
                        {
                            name: "code",
                            label: app.translate(that, "code_label"),
                            editable: false,
                            sortable: false,
                            formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
                                fromRaw: function (rawValue, model) {
                                    return (rawValue) ? app.translate(that, rawValue) : rawValue;
                                }
                            }),
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                            })
                        },
                    ]; 

                    var CustomRow = Backgrid.Row.extend({
                        events: {
                            "click": "onClick"
                        },
                        className: "clickeable-row",
                        onClick: _.debounce(function (e) {
                            var target = $(e.target); 
                            var data_prevent = (target.closest("[data-preventclick]").length > 0) ? target.closest("[data-preventclick]").data("preventclick") : false; 

                            if (!data_prevent) {
                                that.showDelayInfoModal(this.model); 
                            }
                        }, 500, true)
                    });

                    // Initialize a new Grid instance
                    var delays_grid;
                    delays_grid = new Backgrid.Grid({
                        row: CustomRow, 
                        className: "backgrid table table-hover",
                        columns: columns,
                        collection: that.model.get("delaySplits"),
                    });

                    that.$el.find(".delays-grid-container").append(delays_grid.render().el);

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

                    that._startAutoRefresh({ showLoading: true });
                }, true, customPath);
            }, customPath, "main_template");
        }

        , showDelayInfoModal: function (m) {
            if (this.options.demouser) {
                return; 
            }

            var delayinfomodal = new DelayInformationModal.Views.DelayInformationModal({
                viewParams: {
                    rowData: {
                        id: m.get("delayId"),
                        model: m,
                    },
                }
            });

            //calling grid refresh as soon as the modal is hidden in case
            //any changes were made.
            delayinfomodal.on("hidden", this._autoRefresh); 

            delayinfomodal.show();
        }

        , _startAutoRefresh: function (opt) {
            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(opt);
            } catch (Error) { }
        }

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

            this.refresh(_.extend({}, opt, {
                callback: function () {
                    if (that.options.MYREFERENCES.autoRefresh.enabled == true) {
                        that.options.MYREFERENCES.autoRefresh.toid = setTimeout(that._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 (opt) {
            try {
                var that = this;
                var fetched = false; 

                if (opt && opt.showLoading) {
                    setTimeout(function () {
                        if (!fetched) that.showLoading(true);
                    }, 500);
                }

                var lineId = this.options.MYREFERENCES.subviews.subnavbarControls.model.get("lineProductionItemId");
                var machineId = this.options.MYREFERENCES.subviews.subnavbarControls.model.get("machineProductionItemId");
                var productionItemIdFilter = (lineId != -1) ? (machineId != -1) ? machineId : lineId : (machineId != -1) ? machineId : null;

                this.model.get("delaySplits").fetch({
                    data: {
                        productionItemId: productionItemIdFilter,
                        timezone: app.models.user.get("timezoneCode"),
                    },
                    callback: function () {
                        fetched = true; 
                        that.showLoading(false);

                        if (opt && opt.callback && _.isFunction(opt.callback))
                            opt.callback.call(that, that); 
                    }, 
                });
            } catch (Error) { }
        }

        , showLoading: function (val) {
            var loadingPoster = this.$el.find(".loading-poster"); 
            var gridContainer = this.$el.find(".delays-grid-container"); 
            
            if (val) {
                gridContainer.addClass("hide");
                loadingPoster.removeClass("hide");
            } else {
                loadingPoster.addClass("hide");
                gridContainer.removeClass("hide"); 
            }
        }

        , filtersChanged: _.debounce(function () {
            this._autoRefresh({ showLoading: true, refresh: true });
        }, 500)

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

        , 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.options.MYREFERENCES.subviews.subnavbarControls.model, "change:lineProductionItemId", this.filtersChanged);
            this.listenTo(this.options.MYREFERENCES.subviews.subnavbarControls.model, "change:machineProductionItemId", this.filtersChanged);
        }

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

        , unbindViewScopedEvents: function () {

        }

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

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

        , closeSubviews: function () {
            _.each(this.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("subnavbar", true);
            app.models.subnavbar.set("sections", "12");
        }

        , reRender: function () {
            this._startAutoRefresh(); 
        }
    });

    DelaysSimple.Models.SubnavBarControls = Backbone.Epoxy.Model.extend({
        defaults: {
            lineProductionItemId: -1,
            machineProductionItemId: -1,

            lines: [],
            machinesInternal: [],
        },
        computeds: {
            machines: {
                deps: ["lineProductionItemId"],
                get: function () {
                    var line = this.get("lineProductionItemId");
                    var machines = this.get("machinesInternal");

                    return _.map(_.filter(machines, function (m) {
                        if (line != -1) return m.ParentId == line;
                        else return true;
                    }), function (m) {
                        return { value: m.Id, label: m.Name, };
                    });
                },
            }
        },
        initialize: function () {
            this.fetchLinesMachines();
        },
        fetchLinesMachines: function () {
            var that = this;
            Core.Json.CallProcedure(app.DatabaseNames.OEE + ".WebApp.GetProductionItems", null, {
                onSuccess: function (data) {
                    if (data && data.Table) {
                        var items = data.Table;

                        that.set({
                            lines: _.map(_.filter(items, function (m) { return m.ProductionItemType.toUpperCase() == "LINE"; }), function (m) {
                                return { value: m.Id, label: m.Name, };
                            }),
                            machinesInternal: _.filter(items, function (m) { return m.ProductionItemType.toUpperCase() == "MACHINE"; }),
                        });
                    }
                },
                Async: true,
                Secured: true,
            }, app.ConnectionStrings.app);
        },
    });

    //subview for the subnavbar controls
    DelaysSimple.Views.SubnavBarControls = Backbone.Epoxy.View.extend({
        id: "delays-simple-subnavbar-controls"
        , title: ""
        , template: "delays-simple"
        , 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.options.viewModels = {};

            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 + "delays/delays-simple/";

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

                    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 DelaysSimple;

});

