/**
 * Apeman show command.
 * @function apeman.commands.show
 * @param {object} options
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 *
 */
var print = require('../_print'),
    prettyjson = require('prettyjson');

exports = module.exports = function (options, callback) {

    var data = exports._loadProject(),
        namespace = options.namespace || '',
        keysOnly = options.keysOnly;
    var msg = exports._msg(data, namespace, keysOnly);
    print('');
    if (!!namespace) {
        print('namespace: ', namespace, '\n');
    }
    if (keysOnly) {
        print('keys-only: yes\n');
    }
    print(msg);
    print('');
    callback && callback();
};

exports._evaluateGetters = function (data) {
    data && Object.keys(data)
        .forEach(function (key) {
            //Evaluate property getter.
            var value = data[key];
            delete data[key];
            data[key] = value;


            return key;
        });
    return data;
};

exports._cleanCache = function (data) {
    data = exports._evaluateGetters(data);
    data && Object.keys(data)
        .forEach(function (key) {
            var isCache = !!key.match(/^___cached___/);
            if (isCache) {
                delete data[key];
            } else {
                var value = data[key];
                if (typeof(value) === 'object') {
                    data[key] = exports._cleanCache(value);
                }
            }
        });
    return data;
};


exports._msg = function (data, namespaces, keysOnly) {
    if (typeof(namespaces) === 'string') {
        namespaces = namespaces.split('.');
    }
    while (namespaces.length) {
        var namespace = namespaces.shift();
        if (!namespace) break;
        if (!data.hasOwnProperty(namespace)) {
            throw new Error('Unknown namespace: "' + namespace + '"');
        }
        data = data[namespace];
    }
    if (typeof(data) === 'object') {
        data = exports._cleanCache(data);
    }

    if (keysOnly) {
        return Object.keys(data).join('\n');
    } else {
        return prettyjson.render(data);
    }
};

exports._loadProject = require('./../load_project');