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

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

    UploadUpdate.Views.Main = Backbone.View.extend({
        template: "upload-update"
        , id: "upload-update"
        , title: "Upload Update"
        //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 UploadUpdate.Model({
                procedure: "dbo.procedureName"
            });

            this.model = model;

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

        events: {
            "click .btn-upload-file": "uploadUpdate",  
        }, 

        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/upload-update/";

            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;
            }
        }

        , uploadUpdate: function (e) {
            e.preventDefault();

            var that = this;

            $(".btn-upload-file").attr("disabled", true);
            $(".uploading-label").removeClass("hide");

            var fileinput = $("#update_fileinput").get(0);
            var files = fileinput.files;
            var formData = new FormData();

            for (var i = 0; i < files.length; i++) {
                var file = files[i];

                // Add the file to the request.
                formData.append('files[]', file, file.name);
            }

            if (formData) {
                $.ajax({
                    url: app.foldersRoot + "/app/custom-screens/IHConfiguration/upload-update/api/api.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.uploadUpdateProcessHandler, false); // For handling the progress of the upload
                        }
                        return myXhr;
                    },

                    // Form data
                    data: formData,

                    //Options to tell jQuery not to process data or worry about content-type.
                    cache: false,
                    contentType: false,
                    processData: false
                })
                .done(that.uploadUpdateComplete)
                .fail(that.uploadUpdateFailed);
            }

        }
        , uploadUpdateProcessHandler: function (e) {
            var loaded = e.loaded;
            var total = e.total;
            var percent = (loaded * 100) / total;

            this.$el.find(".percent").text(Math.round(percent) + "%");
        }
        , uploadUpdateComplete: function (e) {
            this.$el.find(".percent").text("");
            $(".uploading-label").addClass("hide");
            $(".btn-upload-file").attr("disabled", false);

            if (e.status == "OK") {
                alert("Update Complete"); 
            } else {
                alert("Update Failed");
            }
        }
        , uploadUpdateFailed: function (e) {
            this.$el.find(".percent").text("");
            $(".uploading-label").addClass("hide");
            $(".btn-upload-file").attr("disabled", false);
            alert("Update Failed"); 
        }
        , 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 UploadUpdate;

});
