//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',
    'chart',
    'moment',
    'chartjs-date-fns-adapter',
    'modules/navigation-buttons/navigation-buttons',
    'backgrid/moment-cell',
    'backgrid/grouped-columns',
    'js/multiselect/virtual-select.min',

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

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

    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {
            hasData: true,
            isLoading: false,
            lastPeakUpdated: '',
        },
        initialize: function () {
            this.highestPeaksColl = new Screen.Collections.ItemsColl();
            this.highestAEPLoad = new Screen.Collections.ItemsColl();   
        },
        fetch: function (params) {
            var that = this;
            var qp = new Core.Database.QueryParameters();

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.PWR.GetPeaksWeb',
                qp,
                {
                    onSuccess: function (resp) {
                        try {

                            if (resp && resp.Table) {           
                                that.highestPeaksColl.setDataColl(resp.Table);
                                that.highestAEPLoad.setDataColl(resp.Table1);
                                that.set('lastPeakUpdated', 'Last Metered Update: '+new moment(resp.Table2[0].LastUpdated).format('MM/DD/YYYY HH:mm:SS'));
                            }
                            else {
                                if ((resp) && (resp.Message)) {
                                    app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                    console.error(resp.Message);
                                    that.set({
                                        hasData: false,
                                        isLoading: false,                                       

                                    });

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

                            }


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

            return this;

        },
    });

        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'power-peaks',
            id: 'power-peaks',
            title: 'Power Peaks',
            isCacheable: false,
            events: function () {
                return {
                    'click #refreshBtn': this.refreshBtn_click,
                };
            },
            bindings: 'data-bind',
            subviews: null,
            viewParams: null,
            autoRefresh: null,
            pauseTimer: false,

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

                this.bindEvents();

            },
            bindEvents: function () {
                this.listenTo(this.model.highestAEPLoad, 'fetch', this.process_fetched);

            },

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

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


                                var gridMainInfo = new Backgrid.Grid({
                                    className: 'backgrid table table-hover table-condensed',
                                    columns: [

                                        {
                                            name: 'EventTime',
                                            editable: false,
                                            label: 'Date / Hour',
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell ',
                                            }),
                                        },

                                        {
                                            name: 'RTOMeteredLoad',
                                            editable: false,
                                            label: 'PJM Load',
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'string-cell align-center-cell ',
                                            }),
                                        },     
                                        {
                                            name: 'SDIMeteredLoad',
                                            editable: false,
                                            label: 'SDI Load',
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell ',
                                            }),
                                        },
                                        {
                                            name: 'AveragePrice',
                                            editable: false,
                                            label: 'Price',
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'string-cell align-center-cell ',
                                            }),
                                        },
                                        
                                    ],
                                    header: Backgrid.Extension.GroupedHeader.extend({
                                        columnLayout:
                                            [
                                                {
                                                    name: 'Highest 5 PJM peaks', children:
                                                        [
                                                            { name: 'EventTime' }
                                                            , { name: 'RTOMeteredLoad' }
                                                            , { name: 'SDIMeteredLoad' }
                                                            , { name: 'AveragePrice' }
                                                        ]

                                                },
                                            ],
                                        initialize: function (options) {
                                            Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                        },
                                        render: function () {
                                            var that = this;
                                            Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                            return this;
                                        },
                                    }),
                                    collection: that.model.highestPeaksColl,
                                });
                                that.$el.find('.main-info-grid-container').append(gridMainInfo.render().el);






                                var grid = new Backgrid.Grid({
                                    className: 'backgrid table table-hover table-condensed',
                                    columns: [
                                        {
                                            name: 'EventTime',
                                            editable: false,
                                            label: 'Date / Hour',
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell ',
                                            }),
                                        },
                                        {
                                            name: 'AEPMeteredLoad',
                                            editable: false,
                                            label: 'AEP Load',
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'string-cell align-center-cell ',
                                            }),
                                        },
                                        {
                                            name: 'SDIMeteredLoad',
                                            editable: false,
                                            label: 'SDI Load',
                                            cell: Backgrid.StringCell.extend({
                                                className: 'string-cell align-center-cell ',
                                            }),
                                        },
                                        {
                                            name: 'AveragePrice',
                                            editable: false,
                                            label: 'Price',
                                            cell: Backgrid.NumberCell.extend({
                                                className: 'string-cell align-center-cell ',
                                            }),
                                        },
                                        
                                    ],
                                    header: Backgrid.Extension.GroupedHeader.extend({
                                        columnLayout:
                                            [
                                                {
                                                    name: 'Highest AEP Load', children:
                                                        [
                                                            { name: 'EventTime' }
                                                            , { name: 'AEPMeteredLoad' }
                                                            , { name: 'SDIMeteredLoad' }
                                                            , { name: 'AveragePrice' }
                                                        ]

                                                },
                                            ],
                                        initialize: function (options) {
                                            Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                        },
                                        render: function () {
                                            var that = this;
                                            Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                            return this;
                                        },
                                    }),
                                    collection: that.model.highestAEPLoad,
                                });
                                that.$el.find('.highest-aep-grid-container').append(grid.render().el);




                                that.applyBindings();

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

                                that.refresh();

                                that.startAutoRefresh();

                            },
                            true,
                            customPath
                        );
                    },
                    customPath
                );
            },
            refresh: function (isAutoRefresh) {
                if (!isAutoRefresh) {
                    this.model.set({
                        isLoading: true,
                        hasData: false,
                    });
                }
                else {
                    this.model.set({
                        isLoading: false,
                        hasData: true,
                    });
                }
                

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

        refreshBtn_click: function (e) {
            this.refresh();

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

                if (!this.pauseTimer) {
                    var isAutoRefresh = true;
                    this.refresh(isAutoRefresh);
                } 

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

    });

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


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