/// class PD.Manage.Modules.Actions.ActionSelectionExplorer
// using PD.Web.UI.Controls.Control

PD.Manage.Modules.Actions.ActionSelectionExplorer =
PD.Web.UI.Controls.Control.extend({

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

    _tree: null,
    _plugins: null,

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

    onInit: function () {
        this.getPlugins();
        this._tree_Init();
    },

    onComplete: function () {
        var that = this;
        setTimeout(function () {
            that.selectDefault();
        }, 150)
    },
    
    //===================================
    // 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;padding:0;'></div>",
            "</div>"
        ];
    },

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

    _tree_Init: function () {

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

                var item = e.item || {};

                PD.context
                    .get_default()
                    .get_events()
                    .publish("folder/select", {
                        folderId: item.id
                    });
                
            },
            modules: [
                "PD.Web.UI.Controls.TreeViewSelectionModule"
            ],
            css: {
                position: "absolute",
                top: 0,
                left: 0,
                bottom: 0,
                right: 0
            }
        });

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

    },

    getPlugins: function () {
    
        var plugins = PD.Plugins.PluginManager.getPlugins();
        var data = [];

        _.forEach(plugins, function (o) {
            if (o.get_actions().hasActions()) {
                data[data.length] = { id: o.get_id(), name: o.get_name(), icon: "folder_closed.png", hasChildren: false }
            }
        });

        this._plugins = data;

    },

    selectDefault: function () {

        var plugin = _.first(this._plugins);

        if (plugin == null) {
            return;
        }

        this._tree.expandPath([plugin.id]);

        PD.context
            .get_default()
            .get_events()
            .publish("folder/select", {
                folderId: plugin.id
            });

    }

});