import requests
from datetime import datetime
import pytz


def bit_bucket_user_details(user_name):
    """
    Function to find the bit bucket user details from bit bucket user name.
    :param user_name: string - bit bucket user name
    :return: dict - dictionary of bit bucket user details
    """
    bit_bucket_url = 'https://api.bitbucket.org/2.0/users/%s' % user_name
    bit_bucket_data = requests.get(bit_bucket_url).json()
    date_conversion = bit_bucket_data['created_on'].split('+')[0]
    account_created_at = date_conversion.split('.')
    # account_created_at = datetime.strptime(date_conversion, "%Y-%m-%dT%X").replace(tzinfo=pytz.utc)
    # account_created_at = date_conversion.split('T')
    account_created_at = datetime.strptime(account_created_at[0], "%Y-%m-%dT%X").replace(tzinfo=pytz.utc)
    # account_created_at = datetime.strptime(account_created_at[0], "%Y-%m-%d").date()
    repo_url = list(bit_bucket_data['links']['repositories'].values())[0]
    total_no_of_repos = requests.get(repo_url).json()['size']
    followers_url = list(bit_bucket_data['links']['followers'].values())[0]
    total_no_of_followers = requests.get(followers_url).json()['size']
    following_url = list(bit_bucket_data['links']['following'].values())[0]
    total_no_of_following = requests.get(following_url).json()['size']
    snippets_url = list(bit_bucket_data['links']['snippets'].values())[0]

    user_details = {
        'user_name': user_name,
        'display_name': bit_bucket_data['display_name'],
        'account_created_at': account_created_at,
        'repo_url': repo_url,
        'total_no_of_repos': total_no_of_repos,
        'followers': total_no_of_followers,
        'following': total_no_of_following,
        'blog_url': bit_bucket_data['website'],
        'profile_url': list(bit_bucket_data['links']['html'].values())[0],
        'snippets_url': snippets_url,
        'location': bit_bucket_data['location'],
    }

    return user_details