from urllib import FancyURLopener
import urllib2
import json
import random
from IPython.core.display import Image
from IPython.display import display

class MyOpener(FancyURLopener):
    version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1;\
    it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'

def find_hello_images(search_term,myopener,hello_count=50):   
    count = 0
    search_term = search_term.replace(' ','%20')
    for beer in range(1, hello_count):
        url = 'https://ajax.googleapis.com/ajax/services/search/images?{}{}&start={}&userip=MyIP&imgsz=large'.\
        format('v=1.0&q=',search_term, random.sample(range(60),1)[0])        
        request = urllib2.Request(url, None, {'Referer': 'testing'})
        response = urllib2.urlopen(request)
        results = json.load(response)
        data = results['responseData']
        try:
            data_info = data['results']
        except:
            pass
        for myUrl in data_info:
            count += 1
            yield myUrl['unescapedUrl']
            myopener.retrieve(myUrl['unescapedUrl'])

def collect_images(hello_images, number_of_hello):
    hello_lst = []
    for number,image in enumerate(hello_images, 1):
        hello_lst.append(image)
        if number == number_of_hello:
            return hello_lst

def hello_text(hello_lst, number_of_hello): 
    for hello_count in range(number_of_hello-1, 0, -1):
       if hello_count > 1:
          print "{0} Hello World on the wall, {0} Hello world".format(hello_count)
          print '---'
          hello_lst.pop()          
          for n,img in enumerate(hello_lst, 1):         
              try:
                  image = Image(img)
                  display(image)                                     
              except:
                  pass         
          if hello_count > 2:            
             hello_text = "{} Hello World on the wall.".format(hello_count - 1)
          else:
             hello_text = "1 Hello World on the wall."
       elif hello_count == 1:
          print "1 Hello World on the wall, 1 Hello World"
          image = Image(hello_lst[-1])
          display(image)  
          hello_text = "No more Hello World on the wall!"
       print '---'
       print "Take one down, pass it around,", hello_text

if __name__ == '__main__':
    myopener = MyOpener()
    search_term = "hello world"
    number_of_hello = 6
    hello_img = find_hello_images(search_term, myopener)
    hello_lst = collect_images(hello_img, number_of_hello)
    hello_text(hello_lst, number_of_hello)