from datetime import datetime


def _rebuild_log(log, results, timestamp=None):
    """
    Given results of a search, build an updated version of the log.

    This builds and returns a new log containing only entries present
    in ``results``. Results not previously seen are timestamped with
    the given time; others are passed through unmodified. If no
    timestamp is specified, the current time is used.

    This function also modifies the original log by deleting entries
    that it finds in the results. When it completes, the original log
    can be used as an index of results deleted since the original log
    was built.

    """
    newlog = {}

    if timestamp is None:
        timestamp = datetime.utcnow()

    # rebuild log
    for un, num, snips in results:
        old_snips = log.get(un, {})
        new_snips = {}
        for snip in snips:
            new_snips[snip] = old_snips.pop(
                snip, dict(timestamp=timestamp, unread=True))
        newlog[un] = new_snips

    return newlog