/// class PD.Manage.Modules.Resources.BrowserDropOnTree
// using PD.Web.UI.Controls.GridModule

PD.Manage.Modules.Resources.BrowserDropOnTree =
PD.Web.UI.Controls.GridModule.extend({

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

    _tree: null,
    _dropTargetArea: null,
    
    // PUBLIC METHODS
    //===================================
    //===================================

    start: function () {
        this._super();

        this._tree = $(".-pd-resources-explorer").children(".k-treeview").data("kendoTreeView");

        this._dropTargetArea = this._tree.element.kendoDropTargetArea({
            filter: "LI[data-uid] .k-in",
            drop: $.proxy(this._onDrop, this),
            dragenter: PD.BCL.Util.debounce($.proxy(this._onDragEnter, this), 100),
            dragleave: PD.BCL.Util.debounce($.proxy(this._onDragLeave, this), 100)
        }).data("kendoDropTargetArea");

    },

    unload: function () {
        if (this._dropTargetArea != null) {
            this._dropTargetArea.destroy();
        }
    },

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

    _onDragEnter: function (e) {
        
        var data = this._getEventData(e),
            $hint = $(e.draggable.hint),
            $subtext = $hint.find(".subtext");

        if (data.item != null) {

            $hint.data("shouldHide", false);
            $subtext.show();
            $subtext.html("Move to <b>" + data.item.name + "</b>");

        }

    },

    _onDragLeave: function (e) {

        var $hint = $(e.draggable.hint),
            $subtext = $hint.find(".subtext");

        $hint.data("shouldHide", true);

        setTimeout(function () {
            if ($hint.data("shouldHide") === true) {
                $subtext.hide();
                $subtext.html("");
            }
        }, 200);

    },

    _onDrop: function (e) {

        var data = this._getEventData(e),
            selections = data.selections.toArray(),
            sourceIds = _.map(selections, "id");

        PD.context.get_default().get_commands().execute("pd/resources:resource/move", {
            destination: {
                type: "folder",
                id: data.item.id,
                name: data.item.name,
                mimeType: null
            },
            selections: selections
        });

    },

    _getEventData: function (e) {

        var result = {
                node: $(e.dropTarget).closest("LI"),
                item: null,
                selections: this.get_grid().getSelections()
            },
            tree = this._tree;

        result.item = tree.dataItem(result.node);

        return result;

    }

});