from datetime import datetime


def get_media_insert(media, event):
    """
    Gets all insertion data for a single media object

    Parameters
    ----------
    media: dict
        Dictionary object of a media object
    event: str
        Event name of query the media was retrieved from

    Returns
    -------
    media_insert: dict
        Dictionary of values extracted and formatted for insertion into a
        PostgreSQL database
    """
    # Duration
    try:
        duration_ms = media['duration_ms']
    except KeyError:
        duration_ms = None
    # View count
    try:
        view_count = media['public_metrics']['view_count']
    except KeyError:
        view_count = None
    # Preview
    try:
        preview_url = media['preview_image_url']
    except KeyError:
        preview_url = None

    now = datetime.now()

    media_insert = {
        'id': media['media_key'],
        'event': event,
        'inserted_at': now,
        'last_updated_at': now,
        'type': media['type'],
        'duration_ms': duration_ms,
        'height': media['height'],
        'width': media['width'],
        'preview_image_url': preview_url,
        'view_count': view_count
    }

    return media_insert