//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',
  'moment',
  'modules/navigation-buttons/navigation-buttons',
  'backgrid/moment-cell',
  'js/autocomplete/backbone.autocomplete',
  'backgrid/grouped-columns',

    "js/jquery.floatThead/jquery.floatThead",
    'js/multiselect/virtual-select.min',

],
    function (app, T, Backgrid, moment, NavigationButton) {

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

        Screen.Collections.DynamicGrid = Backbone.Collection.extend({
            setDataColl: function (data) {
                this.set(data);
            }
        });

    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {
            //URL parameters

            heatName: null,
            gradeName: '-',
            time: '-',
            hasData_process: true,
            isLoading_process: false,

            heatId: null,
            direction: null,
            navigation: null,
            heatNames: [],
            enterPress: false,

            appendGrid: true,
        },
        computeds: {
            hasData: {
                deps: ['hasData_process'],
                get: function (process) {
                    return process;
                },
            },
            isLoading: {
                deps: ['isLoading_process'],
                get: function (process) {
                    return process;
                },
            },
        },
        initialize: function () {
            this.grid1Collection = new Screen.Collections.DynamicGrid();
            this.grid2Collection = new Screen.Collections.DynamicGrid();
            this.grid3Collection = new Screen.Collections.DynamicGrid();
            this.grid4Collection = new Screen.Collections.DynamicGrid();
            this.grid5Collection = new Screen.Collections.DynamicGrid();
            this.limitsCompare = null;
        },
        fetch: function (params) {
            var that = this;
            var qp = new Core.Database.QueryParameters();
            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.MES.GetPowerCurtailment',
                qp,
                {
                    onSuccess: function (resp) {
                        try {

                            if (resp) {
                                if (resp.Table) that.grid1Collection.setDataColl(resp.Table);
                                if (resp.Table1) that.grid2Collection.setDataColl(resp.Table1);
                                if (resp.Table2) that.grid3Collection.setDataColl(resp.Table2);
                                if (resp.Table3) that.grid4Collection.setDataColl(resp.Table3);
                                if (resp.Table4) that.grid5Collection.setDataColl(resp.Table4)
                                that.trigger('buildGrid', resp.Table,resp.Table1,resp.Table2,resp.Table3,resp.Table4);
                            }
                            else {
                                if ((resp) && (resp.Message)) {
                                    app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                    console.error(resp.Message);
                                    that.set({
                                        hasData_process: false,
                                        isLoading_process: false,


                                    });
                                }
                                else {
                                    app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                    console.error("Server response not valid.");
                                    that.set({
                                        hasData_process: false,
                                        isLoading_process: false,
                                    });
                                }

                            }


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

            return this;

        },


    });

    Screen.generateID = function (viewParams) {
        try {
            //if the viewparams change the view id, then evaluate the viewparams here
            //and return the appropiate id.refreshbtn
            return 'power-curtailment';
        } catch (Error) { }
    }

    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: 'power-curtailment',
        id: 'power-curtailment',
        title: 'Power Curtailment',
        isCacheable: false,
        events: function () {
            return {
                'click #refreshBtn': this.refreshBtn_click,
            };
        },
        bindings: 'data-bind',
        subviews: null,
        viewParams: null,
        grid1: [],
        grid2: [],
        grid3: [],
        grid4: [],
        grid5: [],
        initialize: function () {
            this.options.state = app.view_states.loading;
            this.options.onappend = (_.isFunction(this.options.onappend)) ? this.options.onappend : function () { };

            var that = this;
            this.model = new Screen.Models.Main();
            this.autoRefresh = {
                enabled: null
                , toid: null
                , every: 15 * 1000
            };

            this.bindEvents();

        },
        bindEvents: function () {
            this.listenTo(this.model.grid1Collection, 'fetch', this.process_fetched);
            this.listenTo(this.model, 'buildGrid', this.buildGrid);
        },
        buildGrid: function (data1,data2,data3,data4,data5) {
            var keys = null,
                columnsName = [];
            var that = this;
            this.model.set({
                appendGrid: false,
            });       
            if (data1 && data1[0]) {
                columnsName = [];
                keys = Object.keys(data1[0]);
                _.each(keys, function (obj) {
                    columnsName.push({
                        "name": obj,
                        "editable": false,
                        "label": app.translate([that, app], obj === 'PJMMaintenance' ? 'PJM Maint' : (obj === 'AEPMaintenance' ? 'AEP Maint' : obj)),
                        "cell": Backgrid.StringCell.extend({
                            className: function () {
                                var model = this.model.toJSON();
                                if (model[obj] === 'OK' || model[obj] === 'ON' || model[obj] === 'MIN PUMP' || model[obj] === 'MIN USE') return 'string-cell align-center-cell ok';
                                else if (model[obj] === 'OFF' || model[obj] === 'Not OK' || model[obj] === 'NOT OK' || model[obj] === 'LOW FIRE' || model[obj] === 'Min Use') return 'string-cell align-center-cell danger';
                                else return 'string-cell align-center-cell';
                            },
                        }),
                    });
                });


                that.grid1 = new Backgrid.Grid({
                    className: 'backgrid table table-hover table-condensed',
                    columns: columnsName,
                    row: Backgrid.Row.extend({
                        initialize: function (options) {
                            Backgrid.Row.prototype.initialize.apply(this, arguments);
                        },
                    }),
                    collection: that.model.grid1Collection
                });
                that.$el.find('.power-curtailment-grid-1-container').append(that.grid1.render().el);
                that.model.set({ grid1: that.grid1 });
            }



            if (data2 && data2[0]) {
                columnsName = [];
                keys = Object.keys(data2[0]);
                _.each(keys, function (obj) {
                    columnsName.push({
                        "name": obj,
                        "editable": false,
                        "label": app.translate([that, app], obj === 'PJMMaintenance' ? 'PJM Maint' : (obj === 'AEPMaintenance' ? 'AEP Maint' : obj)),
                        "cell": Backgrid.StringCell.extend({
                            className: function () {
                                var model = this.model.toJSON();
                                if (model[obj] === 'OK' || model[obj] === 'ON' || model[obj] === 'MIN PUMP' || model[obj] === 'MIN USE') return 'string-cell align-center-cell ok';
                                else if (model[obj] === 'OFF' || model[obj] === 'Not OK' || model[obj] === 'NOT OK' || model[obj] === 'LOW FIRE' || model[obj] === 'Min Use') return 'string-cell align-center-cell danger';
                                else return 'string-cell align-center-cell';
                            },
                        }),
                    });
                });


                that.grid2 = new Backgrid.Grid({
                    className: 'backgrid table table-hover table-condensed',
                    columns: columnsName,
                    row: Backgrid.Row.extend({
                        initialize: function (options) {
                            Backgrid.Row.prototype.initialize.apply(this, arguments);
                        },
                    }),
                    collection: that.model.grid2Collection
                });
                that.$el.find('.power-curtailment-grid-2-container').append(that.grid2.render().el);
                that.model.set({ grid2: that.grid2 });
            }

            if (data3 && data3[0]) {
                columnsName = [];
                keys = Object.keys(data3[0]);
                _.each(keys, function (obj) {
                    columnsName.push({
                        "name": obj,
                        "editable": false,
                        "label": app.translate([that, app], obj === 'PJMMaintenance' ? 'PJM Maint' : (obj === 'AEPMaintenance' ? 'AEP Maint' : obj)),
                        "cell": Backgrid.StringCell.extend({
                            className: function () {
                                var model = this.model.toJSON();
                                if (model[obj] === 'OK' || model[obj] === 'ON' || model[obj] === 'MIN PUMP' || model[obj] === 'MIN USE') return 'string-cell align-center-cell ok';
                                else if (model[obj] === 'OFF' || model[obj] === 'Not OK' || model[obj] === 'NOT OK' || model[obj] === 'LOW FIRE' || model[obj] === 'Min Use') return 'string-cell align-center-cell danger';
                                else return 'string-cell align-center-cell';
                            },
                        }),
                    });
                });


                that.grid3 = new Backgrid.Grid({
                    className: 'backgrid table table-hover table-condensed',
                    columns: columnsName,
                    row: Backgrid.Row.extend({
                        initialize: function (options) {
                            Backgrid.Row.prototype.initialize.apply(this, arguments);
                        },
                    }),
                    collection: that.model.grid3Collection
                });
                that.$el.find('.power-curtailment-grid-3-container').append(that.grid3.render().el);
                that.model.set({ grid3: that.grid3 });
            }


            if (data4 && data4[0]) {
                columnsName = [];
                keys = Object.keys(data4[0]);
                _.each(keys, function (obj) {
                    columnsName.push({
                        "name": obj,
                        "editable": false,
                        "label": app.translate([that, app], obj === 'PJMMaintenance' ? 'PJM Maint' : (obj === 'AEPMaintenance' ? 'AEP Maint' : obj)),
                        "cell": Backgrid.StringCell.extend({
                            className: function () {
                                var model = this.model.toJSON();
                                if (model[obj] === 'OK' || model[obj] === 'ON' || model[obj] === 'MIN PUMP' || model[obj] === 'MIN USE') return 'string-cell align-center-cell ok';
                                else if (model[obj] === 'OFF' || model[obj] === 'Not OK' || model[obj] === 'NOT OK' || model[obj] === 'LOW FIRE' || model[obj] === 'Min Use') return 'string-cell align-center-cell danger';
                                else return 'string-cell align-center-cell';
                            },
                        }),
                    });
                });


                that.grid4 = new Backgrid.Grid({
                    className: 'backgrid table table-hover table-condensed',
                    columns: columnsName,
                    row: Backgrid.Row.extend({
                        initialize: function (options) {
                            Backgrid.Row.prototype.initialize.apply(this, arguments);
                        },
                    }),
                    collection: that.model.grid4Collection
                });
                that.$el.find('.power-curtailment-grid-4-container').append(that.grid4.render().el);
                that.model.set({ grid4: that.grid4 });
            }


            if (data5 && data5[0]) {
                columnsName = [];
                keys = Object.keys(data5[0]);
                _.each(keys, function (obj) {
                    columnsName.push({
                        "name": obj,
                        "editable": false,
                        "label": app.translate([that, app], obj === 'PJMMaintenance' ? 'PJM Maint' : (obj === 'AEPMaintenance' ? 'AEP Maint' : obj)),
                        "cell": Backgrid.StringCell.extend({
                            className: function () {
                                var model = this.model.toJSON();
                                if (model[obj] === 'OK' || model[obj] === 'ON' || model[obj] === 'MIN PUMP' || model[obj] === 'MIN USE') return 'string-cell align-center-cell ok';
                                else if (model[obj] === 'OFF' || model[obj] === 'Not OK' || model[obj] === 'NOT OK' || model[obj] === 'LOW FIRE' || model[obj] === 'Min Use') return 'string-cell align-center-cell danger';
                                else return 'string-cell align-center-cell';
                            },
                        }),
                    });
                });


                that.grid5 = new Backgrid.Grid({
                    className: 'backgrid table table-hover table-condensed',
                    columns: columnsName,
                    row: Backgrid.Row.extend({
                        initialize: function (options) {
                            Backgrid.Row.prototype.initialize.apply(this, arguments);
                        },
                    }),
                    collection: that.model.grid5Collection
                });
                that.$el.find('.power-curtailment-grid-5-container').append(that.grid5.render().el);
                that.model.set({ grid5: that.grid5 });
            }
        },
      


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

            this.viewParams = urlParams;

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

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

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

                            that.applyBindings();

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

                            that.refresh();
                            //that.startAutoRefresh();
                        },
                        true,
                        customPath
                    );
                },
                customPath
            );
        },


        getElementClass: function (value, min, max) {
            if (min === '-') min = null;
            if (max === '-') max = null;
            if (value === '-')
                return 'string-cell align-center-cell no-editable';
            if (value === null)
                return 'string-cell align-center-cell';
            if (!min && !max)
                return 'string-cell align-center-cell ok';
            if (value != null && min && value < min)
                return 'string-cell align-center-cell warning';
            if (value != null && max && value > max)
                return 'string-cell align-center-cell danger';
            if (value != null && max && !min && value <= max)
                return 'string-cell align-center-cell ok';
            if (value != null && min && !max && value >= min)
                return 'string-cell align-center-cell ok';
            if (value != null && min && max && value >= min && value <= max)
                return 'string-cell align-center-cell ok';


        },

        refresh: function () {   
            var that = this;
            this.pauseTimer = true;
            this.model.fetch();

        },           
        process_fetched: function () {
            try {
                var that = this;
                this.pauseTimer = false;
                setTimeout(
                    function () {
                        that.model.set({
                            hasData_process: (that.model.grid1Collection.length > 0),
                            isLoading_process: false,
                        });

                    },
                    100
                );

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

        refreshBtn_click: function (e) {
            this.$el.find('.power-curtailment-grid-container').html('');
            this.model.fetchCatalogs();
            this.refresh();
        },

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

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

                this.autoRefresh.toid = setTimeout(
                    function () { that._refresh(); },
                    this.autoRefresh.every
                );
            }
        },
        startAutoRefresh: function () {
            try {
                if (this.autoRefresh.enabled !== true) {
                    var that = this;

                    if (this.autoRefresh.toid != null) {
                        clearTimeout(this.autoRefresh.toid);
                        this.autoRefresh.toid = null;
                    }

                    this.autoRefresh.enabled = true;

                    //use a timeout to execute the first refresh to return the handle to the start function caller.
                    //So when the caller finish it will do the first refresh.
                    this.autoRefresh.toid = setTimeout(
                        function () { that._refresh(); },
                        1
                    );
                }
            } catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        stopAutoRefresh: function () {
            if (this.autoRefresh.toid != null) {
                clearTimeout(this.autoRefresh.toid);
                this.autoRefresh.toid = null;
            }
            this.autoRefresh.enabled = false;
        },

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

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

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

                this.options.onappend(this);
            }

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

            if (this.options.state == app.view_states.closed) {
                //return without appending.
                return;
            }
        },
        bindViewScopedEvents: function () {
            var that = this;
        },
        unbindViewScopedEvents: function () {

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

            this.stopAutoRefresh();
            this.closeSubviews();
            this.remove();
            this.unbindViewScopedEvents();
            this.unbind();
        },
        closeSubviews: function () {
            _.each(this.subviews, function (sview) {
                sview.close();
            });
        },
        show: function () {
            this.options.state = app.view_states.shown;

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

            this.hideSubviews();

            this.$el.hide();
            this.unbind();
            this.stopListening();
        },
        hideSubviews: function () {
            _.each(this.subviews, function (sview) {
                sview.hide();
            });
        },
        preRender: function () {
            app.models.subnavbar.set("subnavbar", false);
        },
        reRender: function (urlParams) {
            try {
                this.refresh(viewParams);
            } catch (Error) { }
        },

    });


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

