(function() {
    var uuid = require('node-uuid'),
        timer = require('timer-machine');

    module.exports = function(req, resp, next) {
        var id = uuid.v4(),
            log = require(__dirname + '/../libs/log')({
                req_id: id,
                name: 'API'
            });

        req.id = id;
        resp.set('X-Request-Id', id);

        timer.get(id).start();

        req.log = log;

        log.debug('request from %s', req.ip);
        log.info(req.method, req.originalUrl);
        log.info(req.query);
        if (!isEmpty(req.body)) log.info(req.body);

        next();
    };

    function isEmpty(obj) {

        // null and undefined are "empty"
        if (obj === null) return true;

        // Assume if it has a length property with a non-zero value
        // that that property is correct.
        if (obj.length > 0) return false;
        if (obj.length === 0) return true;

        // Otherwise, does it have any properties of its own?
        // Note that this doesn't handle
        // toString and valueOf enumeration bugs in IE < 9
        for (var key in obj) {
            if (hasOwnProperty.call(obj, key)) return false;
        }

        return true;
    }

})();
