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

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

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

    _state: null,
    _splitter: null,
    _explorer: null,
    _browser: null,
    _location: null,
    _selection: null,
    _monitor: null,

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

    init: function (options) {

        this._super($.extend(true, {
            resizable: true,
            selectMode: {
                type: null,
                multiple: false
            },
            config: {
                height: "400px",
                minHeight: "350px",
                width: "700px",
                minWidth: "350px",
                title: "Select Resource"
            }
        }, options));

        this._selection = [];

    },

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

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

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

    get_selectionTextBox: function () {
        return this.get_node().find("INPUT[type=text][data-id=selections]");
    },

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

    onInit: function () {

        var that = this;

        PD.ajax({
            url: PD.Path.resolve("~/Manage/Resources"),
            success: function (data) {
                that._state = {
                    viewStateId: data.viewStateId,
                    preloadNodes: data.preloadNodes
                };
                that._location_monitor_init();
                that._location_init();
                that._explorer_init();
                that._browser_init();
                that._splitter_activate();
            },
            error: function (e) {
                that.error();
                e.errorHandled = true;
            }
        });

    },

    onActivate: function (options) {
        this.get_okButton().on("click", _.bind(this._okButton_onClick, this));
        this.get_canelButton().on("click", _.bind(this._cancelButton_onClick, this));
        this.subscriptions.add("resource/highlight", _.bind(this._resource_onSelect, this));
        this.subscriptions.add("resource/select", _.bind(this._okButton_onClick, this));
    },

    onResize: function () {
        if (this._location != null) {
            this._location.resize();
        }
    },

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

    _okButton_onClick: function () {
        
        this.close({
            command: "ok",
            data: _.extend({
                files: this._selection,
                path: this._location.getPath()
            })
        });
    },

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

    _resource_onSelect: function (e) {

        var that = this,
            selectionText = "",
            selectType = this.get_options()["selectMode"].type,
            hasValidFileSelections = this._hasValidFileSelections(selectType, e),
            hasValidFolderSelections = this._hasValidFolderSelections(selectType, e),
            hasValidSelections = hasValidFileSelections || hasValidFolderSelections;

        this.get_okButton().prop("disabled", !hasValidSelections);

        if (hasValidSelections) {
            this.get_selectionTextBox().val(_.map(e, "name").join(", "));
            this._selection = e;
        }
        else {
            this.get_selectionTextBox().val("");
            this._selection = [];
        }
        
    },

    //===================================
    // PROTECTED METHODS
    //===================================

    template: function (options) {
        return [
            "<div style='position:absolute;top:0;left:0;bottom:0;right:0;overflow:hidden;'>",
                "<div data-id='location' style='position:absolute;box-sizing:border-box;top:10px;height:30px;right:10px;left:10px;'>",
                "</div>",
                "<div style='position:absolute;top:45px;left:10px;bottom:74px;right:10px;overflow:hidden;'>",
                    "<div data-id='splitter' class='-pd-minimal-splitter' style='height:100%;box-sizing:border-box;'>",
                    "</div>",
                "</div>",
                "<div style='position:absolute;height:22px;left:10px;bottom:42px;right:10px;overflow:hidden;'>",
                    "<div style='position:absolute;top:0;left:0;width:100px;height:22px;box-sizing:border-box;border:0 none;font-size:12px;line-height:22px;padding:0 10px 0 0;text-align:right;'>",
                        "File name:",
                    "</div>",
                    "<div style='position:absolute;top:0;left:100px;right:0;height:22px;box-sizing:border-box;border:0 none;'>",
                        "<input type='text' data-id='selections' style='height:20px;width:100%;box-sizing:border-box;border:1px solid #CCCCCC;padding-left:5px;line-height:17px;color:#AAAAAA;' readonly/>",
                    "</div>",
                "</div>",
                "<div class='-pd-dialog-button-deck'>",
                    "<button class='-pd-button' data-id='ok' disabled>OK</button>",
                    "<button class='-pd-button' data-id='cancel'>Cancel</button>",
                "</div>",
            "</div>"
        ];
    },

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

    _splitter_activate: function () {

        var that = this;

        this._splitter = this.get_node().find("[data-id=splitter]").kendoSplitter({
            orientation: "horizontal",
            panes: [
                { size: "200px" },
                {}
            ],
            resize: PD.BCL.Util.debounce(function () {
                that._splitter._resize();
            }, 100)
        }).data("kendoSplitter");

    },

    _explorer_init: function () {

        this._explorer = new PD.Manage.Modules.Resources.ResourceSelectionExplorer({
            insertAt: "DIV[data-id=splitter]",
            preloadNodes: this._state.preloadNodes || []
        });

        this.get_children().add(this._explorer);

    },

    _browser_init: function () {

        this._browser = new PD.Manage.Modules.Resources.ResourceSelectionBrowser({
            insertAt: "DIV[data-id=splitter]",
            viewStateId: this._state.viewStateId,
            extensions: this.get_options()["extensions"],
            selectMode: this.get_options()["selectMode"]
        });

        this.get_children().add(this._browser);
    },

    _location_init: function () {

        this._location = new PD.Manage.Modules.Resources.LocationBar({
            insertAt: "DIV[data-id=location]"
        });

        this.get_children().add(this._location);

    },

    _location_monitor_init: function () {

        this._monitor = new PD.Manage.Modules.Resources.LocationMonitor({});

        this.get_children().add(this._monitor);

    },

    _hasValidFolderSelections: function (selectType, selections) {

        selections = _.isArray(selections) ? selections : [];

        selections = _.countBy(selections, function (selection) {
            return selection.type === "folder" ? "folders" : "files"
        });

        return selectType === null ||
            (selectType === "folders"
                && selections.folders != undefined
                && selections.folders > 0
                && selections.files == null);

    },

    _hasValidFileSelections: function (selectType, selections) {

        selections = _.isArray(selections) ? selections : [];

        selections = _.countBy(selections, function (selection) {
            return selection.type === "folder" ? "folders" : "files"
        });

        return selectType === null ||
            (selectType === "files"
                && selections.files != undefined
                && selections.files > 0
                && selections.folders == null);

    }

});

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