var falafel = require('../');
var vm = require('vm');

var termExps = [
    'Identifier',
    'CallExpression',
    'BinaryExpression',
    'UpdateExpression',
    'UnaryExpression'
].reduce(function (acc, key) { acc[key] = true; return acc }, {});

function terminated (node) {
    for (var p = node; p.parent; p = p.parent) {
        if (termExps[p.type]) return true;
    }
    return false;
}

var src = '{"a":[2,~9,prompt(":d")],"b":4,"c":prompt("beep"),"d":6}';

var offsets = [];
var output = falafel('(' + src + ')', function (node) {
    var isLeaf = node.parent
        && !terminated(node.parent) && terminated(node)
    ;
    
    if (isLeaf) {
        var s = node.source();
        var prompted = false;
        var res = vm.runInNewContext('(' + s + ')', {
            prompt : function (x) {
                setTimeout(function () {
                    node.update(x.toUpperCase());
                }, Math.random() * 50);
                prompted = true;
            }
        });
        if (!prompted) {
            var s_ = JSON.stringify(res);
            node.update(s_);
        }
    }
});

setTimeout(function () {
    console.log(src);
    console.log('---');
    console.log(output);
}, 200);
