/// class PD.Web.UI.SingleUploadDialog
// using PD.Web.UI.Dialog

PD.Web.UI.SingleUploadDialog =
PD.Web.UI.Dialog.extend({

    //===================================
    // FIELDS
    //===================================

    _upload: null,

    //===================================
    // CONSTRUCTOR
    //===================================

    init: function (options) {

        this._super($.extend(true, {
            statusLabel: "Select file to upload...",
            config: {
                resizable: false,
                height: "130px",
                width: "400px",
                title: "Single Upload Dialog"
            },
            filters: null
        }, options));

    },

    //===================================
    // PROPERTIES
    //===================================

    get_okButton: function () {
        return this.get_node().find("BUTTON[data-id=button-ok]");
    },

    get_canelButton: function () {
        return this.get_node().find("BUTTON[data-id=button-cancel]");
    },

    get_selectFilesButton: function () {
        return this.get_node().find("#upload_button");
    },

    get_uploadNameTextbox: function () {
        return this.get_node().find(".selection-textbox");
    },

    //===================================
    // PROTECTED EVENT HANDLERS
    //===================================

    template: function (options) {
        return [
            "<div class='-pd-singleupload-dialog'>",
                "<div id='upload_container' class='-pd-dialog-content'>",
                    "<div class='progress-label'>" + this.get_options().statusLabel + "</div>",
                    "<div class='progress-container'>",
                        "<div class='progress-bar'>&nbsp;</div>",
                        "<div class='progress-bar-background'>&nbsp;</div>",
                    "</div>",
                    "<div class='selection-container'>",
                        "<div class='selection-textbox'></div>",
                        "<input id='upload_button' type='button' value='...' class='selection-button'/>", ,
                    "</div>",
                "</div>",
                "<div class='-pd-dialog-button-deck'>",
                    "<button ",
                        "data-id='button-ok' ",
                        "class='-pdjs-dialog-button'>",
                        "OK",
                    "</button>",
                    "<button ",
                        "data-id='button-cancel' ",
                        "class='-pdjs-dialog-button'>",
                        "Cancel",
                    "</button>",
                "</div>",
            "</div>"
        ];
    },

    onInit: function () {
    },

    onActivate: function (options) {
        this.get_okButton().on("click", $.proxy(this._okButton_onClick, this));
        this.get_canelButton().on("click", $.proxy(this._cancelButton_onClick, this));
        this._upload_activate();
    },

    //===================================
    // PRIVATE EVENT HANDLERS
    //===================================

    _okButton_onClick: function () {
        this._upload.start();
    },

    _cancelButton_onClick: function () {
        this.close();
    },

    _return: function () {

        var value = this._grid.value();

        if (value != null) {
            this.close({
                command: "ok",
                data: value
            });
        }
        else {
            this.close();
        }

    },

    _upload_start: function (e) {
        this._disableButtons(true);
    },

    _upload_filesAdded: function (e) {

        var file = e[0];

        var extension = this._getFileExtension(file.name);

        if (this._isValidExtension(extension)) {
            this.get_uploadNameTextbox().text(file.name);
        }

    },

    _upload_progress: function (e) {
        this.get_node().find(".progress-bar").css({
            width: e.percent + "%"
        });
    },

    _upload_error: function (e) {

        Jade.UI.MessageDialog.open({
            dialogStyle: Jade.UI.MessageDialogStyle.Error,
            dialogButtons: Jade.UI.MessageDialogButtonStyle.OK,
            title: e.error.title,
            message: e.error.message,
            select: (e) => {
                e.close();
                this.close();
            }
        });

        this._disableButtons(false);

    },

    _upload_complete: function (e) {
        this.executePostUploadAction(e);
    },

    _getFileExtension: function (name) {
        return name.slice((name.lastIndexOf(".") - 1 >>> 0) + 2).toLowerCase();
    },

    executePostUploadAction: function (e) {
        var callback = this.get_options()["success"];
        if (_.isFunction(callback)) {
            _.bind(callback, this)(e);
        }
    },

    onUploadError: function (e) {
        //overridable
        this._disableButtons(false);
    },

    //===================================
    // PRIVATE METHODS
    //===================================

    _disableButtons: function (disable) {
        this.get_okButton().prop("disabled", disable);
        this.get_canelButton().prop("disabled", disable)
    },

    _upload_activate: function () {

        this._upload = new PD.Web.UI.Controls.Upload({
            browse_button: "upload_button",
            container: "upload_container",
            multi_selection: false,
            filters: this._getFilters(),
            onFileAdded: _.bind(this._upload_filesAdded, this),
            onUploadStart: _.bind(this._upload_start, this),
            onUploadProgress: _.bind(this._upload_progress, this),
            onUploadComplete: _.bind(this._upload_complete, this),
            onError: _.bind(this._upload_error, this)
        });

        this.get_children().add(this._upload);

    },

    _getFilters: function () {

        var result = [];
        var filters = this.get_options()["filters"];

        if (filters == null) {
            filters = [{ title: "ZIP files", extensions: "zip" }];
        }

        if (!_.isArray(filters)) {
            result[result.length] = filters;
        }
        else {
            result = filters;
        }

        return result;

    },

    _isValidExtension: function (extension) {

        extension = extension.toLowerCase();

        var found = _.find(this._getFilters(), function (item, index) {
            return item.extensions.toLowerCase() == extension;
        });

        return found != null;

    }

});

PD.Web.UI.SingleUploadDialog.open = function (options) {
    return new PD.Web.UI.SingleUploadDialog(options);
}