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

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

    InstallAgent.Views.Main = Backbone.View.extend({
        template: "install-agent"
        , id: "install-agent"
        , title: "Instalar Agente"
        //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 InstallAgent.Model({
                procedure: "dbo.procedureName"
            });

            this.model = model;

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

        events: {
            "click #download_agent_opc": "downloadAgentOPC",
            "click #download_agent_plc": "downloadAgentPLC",
            "click .reset-download-btn": "resetDownload", 
        }, 

        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/install-agent/";

            T.render.call(this, this.template, function (tmp) {

                //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({
                    root: app.foldersRoot
                }));

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

            }, 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;
            }
        }
        , downloadAgentOPC: function () {
            this.downloadAgent({ type: "OPC" }); 
        }
        , downloadAgentPLC: function () {
            this.downloadAgent({ type: "PLC" }); 
        }
        , downloadAgent: function (options) {
            try {
                var that = this;
                var opt = {
                    type: "OPC", 
                };

                opt = _.extend(opt, options); 

                this.$el.find(".download-agent-section-" + opt.type).addClass("hide");
                this.$el.find(".generate-download-progress-section-" + opt.type).removeClass("hide"); 

                $.ajax({
                    url: app.foldersRoot + "/app/custom-screens/IHConfiguration/install-agent/generate-download/generate-download.aspx",
                    type: 'POST',
                    // handle the progress report
                    xhr: function () {  // Custom XMLHttpRequest
                        var myXhr = $.ajaxSettings.xhr();
                        if (myXhr.upload) { // Check if upload property exists
                            myXhr.upload.addEventListener('progress', that.generateDownloadProgress, false); // For handling the progress of the upload
                        }
                        return myXhr;
                    },
                    // Form data
                    data: {
                        accountnumber: app.models.user.get("accountNumber"),
                        sourceName: opt.type, 
                    },
                    dataType: "json"
                })
                .done(function (e) { that.generateDownloadComplete(e, opt); })
                .fail(function (e) { that.generateDownloadFailed(e, opt); });

            } catch (Error) {
            }
        }

        , generateDownloadProgress: function (e) {
        }

        , resetDownload: function (e) {
            var type = $(e.currentTarget).data("type"); 

            this.$el.find(".generate-download-progress-section-" + type).addClass("hide");
            this.$el.find(".download-failed-section-" + type).addClass("hide");
            this.$el.find(".starting-download-section-" + type).addClass("hide");

            this.$el.find(".download-agent-section-" + type).removeClass("hide");
        }

        , generateDownloadFailed: function (e, options) {
            var opt = {
                type: "OPC",
            };

            _.extend(opt, options);

            this.$el.find(".generate-download-progress-section-" + opt.type).addClass("hide");
            this.$el.find(".download-failed-section-" + opt.type).removeClass("hide");
        }

        , generateDownloadComplete: function (e, options) {
            var opt = {
                type: "OPC", 
            }; 

            _.extend(opt, options); 

            this.$el.find(".generate-download-progress-section-" + opt.type).addClass("hide");

            if (e && e.status && e.status == "OK") {
                this.$el.find(".starting-download-section-" + opt.type).removeClass("hide");
                this.$el.find(".download-direct-link-" + opt.type).attr("href", e.path);

                //triger automatic download
                location.href = e.path;
            } else {
                this.$el.find(".download-failed-section-" + opt.type).removeClass("hide");
            }
        }

        , 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 InstallAgent;

});
