import json
from datetime import datetime


def get_user_insert(user, event):
    """
    Gets all insertion data for a single user

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

    Returns
    -------
    user_insert: dict
        Dictionary of values extracted and formatted for insertion into a
        PostgreSQL database
    """
    # Description hashtags
    try:
        hashtags = [hashtag_info['tag'].replace('\x00', '')
                    for hashtag_info in user['entities']['description']['hashtags']]
    except KeyError:
        hashtags = None
    # Description mentions
    try:
        mentions = [mention_info['tag'] for mention_info in user['entities']['description']['mentions']]
    except KeyError:
        mentions = None
    # Description URLs
    try:
        urls = user['entities']['description']['urls']
        urls = [json.dumps(url) for url in urls]
    except KeyError:
        urls = None
    # Profile URL
    try:
        url = user['entities']['url']['urls'][0]['expanded_url']
    except (KeyError, IndexError):
        url = None

    now = datetime.now()

    user_insert = {
        'id': user['id'],
        'event': event,
        'inserted_at': now,
        'last_updated_at': now,
        'created_at': user['created_at'],
        'followers_count': user['public_metrics']['followers_count'],
        'following_count': user['public_metrics']['following_count'],
        'tweet_count': user['public_metrics']['tweet_count'],
        'url': url,
        'profile_image_url': user['profile_image_url'],
        'description_urls': urls,
        'description_hashtags': hashtags,
        'description_mentions': mentions,
        'verified': user['verified']
    }

    for f in ['description', 'location', 'pinned_tweet_id', 'name', 'username']:
        try:
            user_insert[f] = user[f].replace('\x00', '')
        except KeyError:
            user_insert[f] = None

    return user_insert