/// class PD.Manage.Modules.Resources.ResourceSelectionExplorer
// using PD.Web.UI.Controls.Control

PD.Manage.Modules.Resources.ResourceSelectionExplorer =
PD.Web.UI.Controls.Control.extend({

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

    _tree: null,

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

    onInit: function () {

        var that = this;

        this._tree_Init();

        this.subscriptions.add("location/changed", function (e) {
            if (e.source != "explorer") {
                that._tree.expandPath(e.path);
            }
        });

    },

    onComplete: function () {

        var that = this,
            localData = this.get_options()["preloadNodes"];

        delete localData[0].items
        this._tree.addNode(localData[0]);
        this._tree.expandPath(["00000000-0000-0000-0000-000000000000"]);

    },

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

    template: function () {
        return [
            "<div>",
                "<div data-id='tree' style='position:absolute;top:0;left:0;bottom:0;right:0;border:1px solid #DDDDDD;padding:5px;background-color:#FFFFFF;'></div>",
            "</div>"
        ];
    },

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

    _tree_Init: function () {

        var that = this,
            expandPath = [0],
            localData = this.get_options()["preloadNodes"],
            service = new PD.Manage.Services.ResourcesService();

        this._tree = new PD.Web.UI.Controls.TreeView({
            insertAt: "[data-id=tree]",
            dragAndDrop: false,
            remoteData: {
                read: function (e) {

                    var item = e.item;

                    if (item) {
                        service.getFolders(item.id, function (result) {
                            e.success(result);
                        });
                    }

                }
            },
            onChange: function (e) {

                var item = e.item || {};

                PD.context
                    .get_default()
                    .get_events()
                    .publish("location/change", {
                        folderId: item.id,
                        source: "explorer"
                    });

            },
            modules: [
                "PD.Web.UI.Controls.TreeViewSelectionModule"
            ],
            css: {
                position: "absolute",
                top: 0,
                left: 0,
                bottom: 0,
                right: 0
            }
        });

        this.get_children().add(this._tree);

    }

});