/**
 * Generate a json file from a seed file.
 * @function CI.worker._evaluateSeedEntry
 * @param {object} seedEntry - Seed entry object.
 * @param {object} scopeData - Evaluate scope data.
 * @returns {object} Evaluated data.
 * @author Taka Okunishi
 * @protected
 * @ignore
 */
var expression = require('../../lib/expression'),
    evaluateScriptWithScope = expression.evaluateScriptWithScope;
exports = module.exports = function (seedEntry, scopeData) {
    var result = (seedEntry instanceof Array) ? [] : {};
    for (var key in seedEntry) {
        if (!seedEntry.hasOwnProperty(key)) continue;
        var val = seedEntry[key];
        switch (typeof(val)) {
            case 'string':
                result[key] = exports._evaluateStringProperty(val, scopeData);
                break;
            case 'object':
                result[key] = exports(val);
                break;
            case 'function':
                result[key] = val(scopeData);
                break;
            default :
                result[key] = val;
        }
    }
    return result;
};

exports._evaluateStringProperty = function (val, scopeData) {
    return val.replace(/(\$\{)(.*?)(\})/g, function ($0, $1, $2) {
        try {
            var value = evaluateScriptWithScope($2, scopeData);
            if (value instanceof Function) {
                return eval($2.replace(/;$/, '') + '()');
            } else {
                return  value;
            }
        } catch (e) {
            throw new Error("Failed to evaluate expression: '" + $0 + "'", e);
        }
    });
};