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

],

function (app, T, Modal) {

    //replace all "ResetToFactoryDefaults" with your view's name.
    var ResetToFactoryDefaults = { Model: {}, Views: {} }

    ResetToFactoryDefaults.Model = Backbone.Model.extend({
        defaults: {
            procedure: ''
        }
    });

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

    ResetToFactoryDefaults.Views.Main = Backbone.View.extend({
        template: "reset-to-factory-defaults"
        , id: "reset-to-factory-defaults"
        , title: "Reset to Factory Defaults"
        //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 ResetToFactoryDefaults.Model({
                procedure: "dbo.procedureName"
            });

            this.model = model;

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

        events: {
            "click #reset_to_factory_defaults_btn": "resetToFactoryDefaults",
        }, 

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

            //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/custom-screens/IHConfiguration/reset-to-factory-defaults/";

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

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

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

        , 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;
            }
        }
        , resetToFactoryDefaults: function () {
            var that = this;

            var modal = new Modal.Views.Main({
                id: "reset-to-factory-defaults-modal"
                , title: this.options.i18n[this.template].translate("confirmation_modal_title").fetch()
                , message: this.options.i18n[this.template].translate("confirmation_modal_msg").fetch()
                , allowCancel: true
                , buttons_type: "CONTINUE-CANCEL"
            });

            modal.on("continue", function () {

                var loading_modal = new Modal.Views.Main({
                    id: "loading-modal"
                    , title: ""
                    , content: that.$el.find("#reset_to_factory_loading_modal_template").html()
                    , allowCancel: false
                    , buttons_type: ""
                });

                loading_modal.on("shown", function () {
                    setTimeout(function () {
                        $.ajax({
                            url: app.foldersRoot + "/app/custom-screens/IHConfiguration/reset-to-factory-defaults/api/factory-defaults-api.aspx",
                            type: 'POST',
                            // Form data
                            data: {
                                action: "RESET_TO_FACTORY_DEFAULTS",
                            },
                            dataType: "json",
                            success: function (e) {
                                if (e.Success) {
                                    app.router.logout();
                                } else {
                                    alert("Failed when trying to reset to factory defaults. Please try again."); 
                                    loading_modal.hide(); 
                                }
                            },
                            error: function (e) {
                                console.log("Error calling API to reset to factory defaults.");
                            },
                        });
                    }, 1500); 
                });

                loading_modal.show(); 
            }); 

            modal.show();
        }

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

        , preRender: function () {
            app.models.subnavbar.set("dateControl", false);
            app.models.subnavbar.set("subnavbar", false);
        }

        , reRender: function () {
        }
    });

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

});
