import re
import requests
import json


def search_HN(current_month):
    """
    This function will send to HackerNews a search request for "Who is Hiring
    (current_month current_year)".  It will then search through the search
    results and find the correct HackerNews item page and return its item ID.

    Args:
        current_month {str} : Month for Search in MMMM YYYY format.
    Returns:
        Hacker News Item ID
    """

    # Set up the query
    query = 'http://hn.algolia.com/api/v1/search?query=Whois+Hiring+(' \
            + current_month \
            + ')&tags=story'
    query = re.sub(r'\s+', r'+', query)

    # Send query and search for the item ID
    print('Searching HackerNews for Who is Hiring pages for %s'
          % (current_month))
    r = requests.get(query).text
    j = json.loads(r)

    # Search through the hits for the correct title
    for hit in j['hits']:
        if hit['title'] == 'Ask HN: Who is hiring? (' + current_month + ')':
            print('Found item ID!: %s' % (hit['objectID']))
            return hit['objectID']

    # Return None if unable to find the correct title anywhere.
    raise Exception('Unable to Locate for %s' % (current_month))