/// class PD.Manage.Modules.Resources.UploadFilesDialog
// using PD.Web.UI.Dialog

PD.Manage.Modules.Resources.UploadFilesDialog =
PD.Web.UI.Dialog.extend({

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

    _grid: null,
    _upload: null,

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

    init: function (options) {

        this._super($.extend(true, {
            config: {
                height: "400px",
                minHeight: "350px",
                width: "600px",
                minWidth: "350px",
                title: "Upload Files",

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

    get_uploadContainer: function () {
        return this.get_node().find("#resource_upload_container");
    },

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

    template: function (options) {
        return [
            "<div style='position:absolute;top:0;bottom:0;left:0;right:0;'>",
                "<div data-id='grid-wrap' style='position:absolute;top:10px;bottom:44px;left:10px;right:10px;' class='-pd-grid-wrap'>",
                "</div>",
                "<div id='resource_upload_container' style='position:absolute;top:10px;bottom:44px;left:10px;right:10px;border:0 none;overflow:hidden;background-color:#FFFFFF;border:1px solid #DDDDDD;'>",
                    "<table style='height:100%;width:100%;'>",
                        "<tr>",
                            "<td style='text-align:center;vertical-align:middle;'>",
                                "<button id='resource_upload_button' style='font-size:12px;'>",
                                    "<img src='" + PD.Path.to48x48("folder_into.png") + "'/><br/>",
                                    "Select Files...",
                                "</button>",
                            "</td>",
                        "</tr>",
                    "</table>",
                "</div>",
                "<div style='position:absolute;bottom:10px;left:10px;right:10px;text-align:right;'>",
                    "<button ",
                        "data-id='button-ok' ",
                        "class='-pd-button' ",
                        "style='margin-right:5px;'>",
                        "OK",
                    "</button>",
                    "<button ",
                        "data-id='button-cancel' ",
                        "class='-pd-button'>",
                        "Close",
                    "</button>",
                "</div>",
            "</div>"
        ];
    },

    onInit: function () {
        this._grid_init();
    },

    onActivate: function (options) {
        this.get_okButton().on("click", _.bind(this._okButton_onClick, this));
        this.get_canelButton().on("click", _.bind(this._cancelButton_onClick, this));
        this._disableButtons(true);
        this._upload_init();
    },

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

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

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

    _upload_filesAdded: function (e) {

        var ds = this._grid.get_dataSource().get_instance(),
            data = null;;

        data = _.map(e, function (item) {
            return {
                id: item.id,
                icon: "~/areas/shared/assets/internal/icons/16x16/folder_open.png",
                name: item.name,
                progress: item.percent,
                status: 1
            };
        });

        ds.data(data);

        this._grid.get_kendo().refresh();

        if (data.length === 0) {
            this._showContainer();
        }
        else {
            this._hideContainer();
        }

        this._disableButtons(false);

    },

    _upload_file_uploaded: function (e) {

        var ds = this._grid.get_dataSource().get_instance(),
            file = ds.get(e.id);

        if (file) {
            file.set("status", e.status);
        }

    },

    _upload_progress: function (e) {

        var ds = this._grid.get_dataSource().get_instance(),
            file = ds.get(e.id);

        if (file) {
            file.set("progress", e.percent);
            file.set("status", e.status);
        }

    },

    _upload_complete: function (e) {
        this._executeAddFileServiceMethod(this.get_options().data.currentFolderId, e, 0);
    },

    _upload_error: function (e) {

        var that = this;

        PD.Web.UI.MessageDialog.warn({
            title: e.error.title,
            message: e.error.message,
            noCancel: true,
            ok: function (e) {
                e.close();
                that.close();
            }
        });

        this._disableButtons(false);

    },

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

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

    _grid_init: function () {

        var status_icons = {
            1: PD.Path.to16x16("hourglass.png"),
            2: PD.Path.toMisc("loading-16x16.gif"),
            4: PD.Path.to16x16("sign_warning.png"),
            5: PD.Path.to16x16("ok.png")
        };

        this._grid = new PD.Web.UI.Controls.Grid({
            insertAt: "[data-id=grid-wrap]",
            pk: "id",
            selectOnRightClick: true,
            resizable: true,
            dataSource: {
                data: []
            },
            footer: {
                visible: false
            },
            columns: [
                new PD.Web.UI.Controls.GridIconColumn({
                    field: "icon"
                }),
                new PD.Web.UI.Controls.GridColumn({
                    field: "name",
                    title: "Name"
                }),
                new PD.Web.UI.Controls.GridProgressColumn({
                    field: "progress",
                    title: "Progress",
                    width: "100px"
                }),
                new PD.Web.UI.Controls.GridColumn({
                    field: "progress",
                    title: "&nbsp;",
                    width: "30px",
                    attributes: {
                        style: "background-color:white;border:1px solid \\#EEEEEE;border-width:0 1px 1px 0;text-align:center;padding:5px 0 0 0;"
                    },
                    template: function (e) {
                        return "<img src='" + status_icons[e.status] + "' />";
                    }
                })
            ]
        });

        this.get_children().add(this._grid);

    },

    _upload_init: function () {

        this._upload = new PD.Web.UI.Controls.Upload({
            browse_button: "resource_upload_button",
            container: "resource_upload_container",
            onFileAdded: _.bind(this._upload_filesAdded, this),
            onFileUploaded: _.bind(this._upload_file_uploaded, 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);

    },

    _handleDuplicateFilesError: function (folderId, files, fileMode) {

        var that = this;

        return new PD.Manage.Modules.Resources.Dialogs.showDuplicateFilesDialog(function (e) {
            e.close();
            that._executeAddFileServiceMethod(folderId, files, e.value);
        });

    },

    _executeAddFileServiceMethod: function (folderId, files, fileMode) {

        var that = this,
            service = new PD.Manage.Services.ResourcesService();

        var message = new PD.Web.UI.Controls.LoadScreen({
            insertAt: "DIV[data-id=grid-wrap]",
            size: "medium",
            message: "Completing the file add process, please wait..."
        });

        this.get_children().add(message);

        this.get_canelButton().prop("disabled", true);

        service.addFiles(folderId, files, fileMode, function (args) {
            that.close({
                command: "ok"
            });
        }, function (args) {

            args.errorHandled = true;

            var failedFiles = _.map(args.failed, function (failed) {
                return failed.file;
            });

            if (_.includes(args.errorCodes, 2)) {
                that._handleDuplicateFilesError(folderId, failedFiles, fileMode);
            }

            message.remove();

            that.get_canelButton().prop("disabled", false);

        });

    },

    _hideContainer: function () {
        this.get_uploadContainer().css({ height: 0, width: 0 });
    },

    _showContainer: function () {
        this.get_uploadContainer().css({height: "auto", width: "auto"});
    }

});

PD.Manage.Modules.Resources.UploadFilesDialog.open = function (options) {
    return new PD.Manage.Modules.Resources.UploadFilesDialog(options);
};