/// class PD.Commands.CommandManager

PD.Commands.CommandManager =
Class.extend({

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

    _groups: null,
    _contexts: null,

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

    init: function () {
        this._contexts = new PD.Commands.CommandContextCollection(this);
        this._registrations = {};
    },

    //===================================
    // PUBLIC PROPERTIES
    //===================================

    get_registrations: function () {
        return PD.Commands.CommandRegistrar.get_registrations();
    },

    get_contexts: function () {
        return this._contexts;
    },

    get_currentContextId: function () {
        return this.get_contexts().get_currentContextId();
    },

    //===================================
    // PUBLIC METHODS
    //===================================

    setContext: function (contextId) {
        this._contexts.current(contextId);
    },

    setState: function (state, contextId) {

        var context = null;

        if (contextId != null) {
            context = this.get_contexts().getById(contextId);
        }
        else {
            context = this.get_contexts().current();
        }

        if (context != null) {
            context.setState(state);
        }

    },

    execute: function (commandPath, args) {

        var resolved = this.resolvePath(commandPath);

        if (resolved.group != null) {
            resolved.group.execute(commandPath, args);
        }

    },

    resolvePath: function (commandPath) {
    
        var resolved = PD.Commands.CommandUtil.splitPath(commandPath),
            context = this.get_contexts().getById(resolved.contextId),
            group = null,
            command = null;

        if (!context) {
            context = this.get_contexts().current();
        }

        if (context) {
            group = context.ensureGroup(resolved.groupId);
        }

        if (group) {
            command = group.get_commands().getById(resolved.commandId);
        }

        return {
            context: context,
            group: group,
            command: command,
            path: commandPath
        };

    },

    registerGroup: function (id, type) {
        PD.Commands.CommandRegistrar.registerGroup(id, type);
        //this._registrations[id] = type;
    }

});