import logging


def get_labels(events, labels=None):
    """
    Determine the labels applied to an issue.

    Args:
        events: a list of (event_type str, event_body dict, timestamp).
    Returns:
        labels: the currently applied labels as {label_name: label_color}
    """
    labels = labels or {}
    for event, body, _timestamp in events:
        if 'issue' in body:
            # issues come with labels, so we can update here
            labels = {l['name']: l['color'] for l in body['issue']['labels']}
        # pull_requests don't include their full labels :(
        action = body.get('action')
        if event == 'pull_request':
            # Pull request label events don't come with a full label set.
            # Track them explicitly here.
            try:
                if action in ('labeled', 'unlabeled') and 'label' not in body:
                    logging.warning('label event with no labels (multiple changes?)')
                elif action == 'labeled':
                    label = body['label']
                    if label['name'] not in labels:
                        labels[label['name']] = label['color']
                elif action == 'unlabeled':
                    labels.pop(body['label']['name'], None)
            except:
                logging.exception('??? %r', body)
                raise
    return labels