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

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

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

    
        Screen.Models.Main = Backbone.Epoxy.Model.extend({
            defaults: {
                casterCodes: [{ label: '1', value: 1 }],
                casterCode: 1,

                //URL parameters

                heatName: '-',

                hasData_process: false,
                isLoading_process: false,


                hasData_strands: false,
                isLoading_strands: false,


                processId: null,
                heatId: null,
                direction: null,
                navigation: null,
                heatNames: [],
                enterPress: false,
            },
            computeds: {
                hasData: {
                    deps: ['hasData_process'],
                    get: function (process) {
                        return true;
                    },
                },
                isLoading: {
                    deps: ['isLoading_process'],
                    get: function (process) {
                        return false;
                    },
                },
            },
    });
    Screen.generateID = function (viewParams) {
        try {
            //if the viewparams change the view id, then evaluate the viewparams here
            //and return the appropiate id.refreshbtn
            return 'caster-tracking-testing';
        } catch (Error) { }
    }

        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'caster-tracking-testing',
            id: 'caster-tracking-testing',
            title: 'Caster Tracking Testing',
            isCacheable: false,
            events: function () {
                return {
                    'click #refreshBtn': this.refreshBtn_click,
                    'click #backNavBtn': this.backNavBtn_click,
                    'click #forwardNavBtn': this.forwardNavBtn_click,
                    'keyup #search': this.keyPressEventHandler,
                    'click #printBtn': this.printBtn_click,
                };
            },
            bindings: 'data-bind',
            subviews: null,
            viewParams: null,

            casterChart: null,
            NavigationButtonView: null,

            initialize: function () {
                this.options.state = app.view_states.loading;
                this.options.onappend = (_.isFunction(this.options.onappend)) ? this.options.onappend : function () { };

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

                this.bindEvents();

            },
            bindEvents: function () {
                this.listenTo(this.model, 'change:processId', this.processIdChanged);

            },


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

                                that.applyBindings();

                                //Trending
                                that.casterChart = new IndustrialChart(
                                    that.$el.find('#casterChartContainer')[0],
                                    {
                                        View: {
                                            Title: app.translate([that, app], 'process_chart_title'),
                                            Header: false,
                                            DisplayScales: {
                                                value: false,
                                            },
                                            Resize: false,
                                            Configuration: {
                                                CursorValue: true,
                                            },
                                        },
                                        DatabaseParameters: {
                                            ConnectionStringName: app.ConnectionStrings.app,
                                            Procedure: app.DatabaseNames.MES + '.CAS.GetTrackingTestingChartData',
                                            Secured: true,
                                        },
                                    }
                                );


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

                             
                                var fixedParams = _.extend({}, urlParams);
                                if (fixedParams.processId)
                                    fixedParams.processId = urlParams.processId ? parseInt(urlParams.processId, 10) : null;

                                that.model.set(fixedParams);

                                that.refresh();

                            },
                            true,
                            customPath
                        );
                    },
                    customPath
                );
            },

            refresh: function () {

                this.processIdChanged();
            },

            processIdChanged: function () {
                var params = this.model.toJSON(),
                    qp = new QueryParameters();

                qp.Add('id', 'INT', params.processId ? params.processId : null);
                if (this.casterChart) {
                    this.casterChart.Clear();
                    this.casterChart.RefreshData(qp);
                   
                }
            },

         
            UpdateURL: function () {
                try {
                    var params = this.model.toJSON();
                    app.router.navigate(
                        app.router.resolveURL(
                            app.router.currentModule,
                            _.extend(
                                {},
                                params,
                                {
                                    processId: params.processId,
                                }
                            ),
                            false
                        ),
                        { trigger: false, }
                    );
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },

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

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