//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 "ResetToFactoryDefaultsIHDelays" with your view's name.
    var ResetToFactoryDefaultsIHDelays = { Model: {}, Views: {} }

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

    ResetToFactoryDefaultsIHDelays.Views.Main = Backbone.View.extend({
        template: "reset-to-factory-defaults-ih-delays"
        , id: "resettofactorydefaultsihdelays"
        , 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 ResetToFactoryDefaultsIHDelays.Model({
            });

            this.model = model;

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

        events: {
            "click .btn-reset-ih-delays-data": "resetIHDelaysData",
            "click .btn-reset-ih-delays-data-configurations": "resetIHDelaysDataAndConfigurations", 
        }, 

        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/IHDelaysConfiguration/reset-to-factory-defaults-ih-delays/";

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

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

            modal.on("continue", function () {
                app.CallProcedure(app.DatabaseNames.IHDelays + ".WebApp.ClearIHDelaysData", null, {
                    onSuccess: function (data) {
                        if (data && data.Table && data.Table[0]) {
                            var status = data.Table[0].Status; 
                            if (status == 'OK') {
                                app.views.topMessages.showMessage(that.options.i18n[that.template].translate("reset_data_success_message").fetch(), { stay: 3000 });
                            } else {
                                //something failed
                                app.views.topMessages.showMessage(that.options.i18n[that.template].translate("reset_data_failed_message").fetch(), { stay: 3000 });
                            }
                        } else {
                            //something failed!
                            app.views.topMessages.showMessage(that.options.i18n[that.template].translate("reset_data_failed_message").fetch(), { stay: 3000 });
                        }
                    },
                    onError: function(data){
                        //something failed
                        app.views.topMessages.showMessage(that.options.i18n[that.template].translate("reset_data_failed_message").fetch(), { stay: 3000 });
                    }, 
                    Secured: true,
                }, app.ConnectionStrings.app);
            });

            modal.show(); 
        }
        , resetIHDelaysDataAndConfigurations: function () {
            var that = this;

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

            modal.on("continue", function () {
                app.CallProcedure(app.DatabaseNames.IHDelays + ".WebApp.ClearIHDelaysDataAndConfigurations", null, {
                    onSuccess: function (data) {
                        if (data && data.Table && data.Table[0]) {
                            var status = data.Table[0].Status;
                            if (status == 'OK') {
                                app.views.topMessages.showMessage(that.options.i18n[that.template].translate("reset_data_and_configurations_success_message").fetch(), { stay: 3000 });
                            } else {
                                //something failed
                                app.views.topMessages.showMessage(that.options.i18n[that.template].translate("reset_data_and_configurations_failed_message").fetch(), { stay: 3000 });
                            }
                        } else {
                            //something failed!
                            app.views.topMessages.showMessage(that.options.i18n[that.template].translate("reset_data_and_configurations_failed_message").fetch(), { stay: 3000 });
                        }
                    },
                    onError: function (data) {
                        //something failed
                        app.views.topMessages.showMessage(that.options.i18n[that.template].translate("reset_data_and_configurations_failed_message").fetch(), { stay: 3000 });
                    },
                    Secured: true,
                }, app.ConnectionStrings.app);
            });

            modal.show();
        }
        , resetToFactoryDefaults: function () {
            var that = this;

            var modal = new Modal.Views.Main({
                id: "reset-to-factory-defaults-ih-delays-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/OEEConfiguration/reset-to-factory-defaults-ih-delays/api/factory-defaults-api.aspx",
                            type: 'POST',
                            // Form data
                            data: {
                                action: "RESET_TO_FACTORY_DEFAULTS",
                            },
                            dataType: "json"
                        })
                        .done(function (e) {
                            app.router.logout();
                        });
                    }, 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 ResetToFactoryDefaultsIHDelays;

});
