/// class PD.Commands.CommandContext

PD.Commands.CommandContext =
Class.extend({

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

    _id: null,
    _manager: null,

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

    init: function (options) {
        this._id = options.contextId;
        this._groups = new PD.Commands.CommandGroupCollection();
    },

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

    get_groups: function () {
        return this._groups;
    },

    //===================================
    // PUBLIC METHODS
    //===================================
    
    setState: function (state) {

        var group = null,
            key = null;

        for (key in state) {

            group = this.get_groups().getById(key);

            if (group == null) {
                group = this.ensureGroup(key);
            }

            if (group != null) {
                group.setState(state[key]);
            }

        }

    },

    ensureGroup: function (groupId) {
    
        var result = null,
            type = null,
            registrations = PD.Commands.CommandRegistrar.get_registrations();

        if (groupId != null && groupId in registrations) {
            type = registrations[groupId];
            if (type != null) {
                if (!this.get_groups().groupIsDefined(groupId)) {
                    result = new type({
                        id: groupId,
                        contextId: this._id
                    });
                    this.get_groups().add(result);
                }
                else {
                    result = this.get_groups().getById(groupId);
                }
            }
        }

        return result;

    },

    resolve: function (commandPath) {

        var resolved = PD.Commands.CommandUtil.splitPath(commandPath),
            group = this.ensureGroup(resolved.groupId),
            command = null;

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

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

    },

    execute: function (commandPath, args) {

        var resolved = this.resolve(commandPath);

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

    },

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

    _mergeState: function (oldState, newState) {
        for (var key in newState) {
            oldState[key] = newState[key];
        }
        return oldState;
    }

});