#!/Users/simms8/anaconda2/bin/python
#
#NAME:
#  test_imdb.py
#
#PURPOSE:
#  To test out the retrieval of IMDB title based off of 
#  a filename. 
#
#EXAMPLES:
#
import os
import re
import sys
import pdb
import requests
rootdir = './'
moviename = 'ghostbusters'

# Start a session
r=requests.Session()

# Get rid of the .mkv extension
print ""
print "Searching IMDB for the movie : " + moviename

# Form the URL and make the query
url = "http://www.imdb.com/find?ref_=nv_sr_fn&q="+moviename+"&s=all"
res=r.get(url)

# Manipulate the text so that we can get the right name
res=res.text.encode('utf8', 'replace')
res=res.replace('</a>', '')
start = res.find("ref_=fn_al_tt_1")
total_titles   = 4
this_title_num = 0
newfilenames = []
while ((this_title_num < total_titles) and (start != -1)):
  # If there was no match at all, exit 
  if ((this_title_num == 0) and (start == -1)):
    print "Could not find matching text! Skipping..."
    break
  else:
    start = res.find("ref_=fn_al_tt_"+str(this_title_num+1), start+1)
    offset = 18
    newfilenames.append(res[start+offset: res.find(' </td>', start)])
    print "New file name is : " + newfilenames[this_title_num]
    this_title_num+=1
    # Look for the next instance
    start = res.find("ref_=fn_al_tt_"+str(this_title_num+1), start+1)
pdb.set_trace()
