import json


def filter_line(lang, tweet_line):
    """Returns tweet if it is in 'lang' language.

    Tweet includes text, lang, entities and tweet id.

    Args:
        lang: string
            BCP 47 language identifier
        tweet_line: JSON object
            represents one tweet

    Returns: A dictionary
    """
    try:
        tweet = json.loads(tweet_line)
    except:
        return None

    # sanity check
    if 'lang' not in tweet or 'text' not in tweet:
        return None

    # make sure there are no empty tweets
    if not tweet['text']:
        return None

    # filter based on language
    if tweet['lang'] != lang:
        return None

    # extract useful properties
    ntweet = {'text': tweet['text'], 'lang': tweet['lang']}
    if 'entities' in tweet:
        ntweet['entities'] = tweet['entities']
    if 'id' in tweet:
        ntweet['id'] = tweet['id']
    elif 'id_str' in tweet:
        ntweet['id'] = int(tweet['id_str'])
    if 'created_at' in tweet:
        ntweet['created_at'] = tweet['created_at']
    if 'retweeted_status' in tweet:
        ntweet['retweet_id'] = int(tweet['retweeted_status']['id_str'])
    if 'retweet_id' in tweet:
        ntweet['retweet_id'] = int(tweet['retweet_id'])

    return ntweet