#!/usr/bin/python
#
#NAME:
#  rename_mkv_with_imdb_lf.py
#
#PURPOSE:
#  To go through all of the subdirectories in the current directory 
#  and rename the primary movie file (as determined by file size)
#  with the correct imdb title so that Kodi will understand it 
#
#EXAMPLES:
#  > cd [MOVIE_DIRECTORY]
#  /Users/lances/python_scripts/rename_mkv_with_imdb_lf.py
#
import os
import re
import sys
import pdb
import requests
rootdir = './'

print '------------------------------------------------------------------------------------'
print '------------------------------------------------------------------------------------'
print 'Looping through all subdirectories in current working directory and looking for     '
print 'the largest file.'
print '------------------------------------------------------------------------------------'
print '------------------------------------------------------------------------------------'

for root, directories, filenames in os.walk(rootdir):

  #Scan through the subdirectories of the rootdir 
  for directory in directories:

    # Print out the current directory
    print ''
    print '------------------------------------------------------------------------------------'
    print 'DIRECTORY: ' + directory 

    # Ask to skip the directory
    print 'Press 1 to enter directory; any other number to skip...'
    Choice = '0'
    while (type(Choice) != int):
      try:
        Choice = int(raw_input())
      except KeyboardInterrupt
        sys.exit()
      except:
        print 'That is not a valid input. You must input a number between 0 and 9'
  
    # YES: we want to descend into the directory
    if (Choice == 1):

      # Now go through each directory and look for the jpg
      for root2, directories2, filenames2 in os.walk(os.path.join(root,directory)):

        # Determine the largest file first and record its path and name
        fs_sofar = 0
        for filename2 in filenames2:
          thispath = os.path.join(rootdir, directory, filename2)
          size = os.path.getsize(thispath)
          if (size > fs_sofar):
            fs_sofar = size
            olddir  = os.path.join(rootdir, directory)
            oldpath = thispath
            oldname = filename2

        # Alert the user and give him/her the option to search 
        print ''
        print 'Directory    : ' + olddir
        print 'Largest file : ' + oldname
        print ''

        # Get the extension and the file extension
        movie_try, extension = os.path.splitext(oldname)
        print 'Searching IMDB for the movie : ' + movie_try
 
        # Start a session
        r=requests.Session()

        # Form the URL and make the query
        url = 'http://www.imdb.com/find?ref_=nv_sr_fn&q='+movie_try+'&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>', '')

        # Now begin searching for titles, which come after href tags that have links  
        # ending in the sequence '?ref=fn_al_tt_#', where number is an integer index
        offset = 18
        total_titles   = 4
        this_title_num = 0
        newfilenames = []
        start = 0

        # Loop over all the matching titles
        while ((this_title_num < total_titles) and (start != -1)):

          # Look for the next instance of a title
          start = res.find('ref_=fn_al_tt_'+str(this_title_num+1), start+1)
          if (start == -1): break
          # If there was no match at all, exit
          if ((this_title_num == 0) and (start == -1)):
            print 'Could not find matching text! Skipping...'
            break
          # If there was a match, add the title to the list
          else:
            start = res.find('ref_=fn_al_tt_'+str(this_title_num+1), start+1)
            end = res.find(' </td>', start)
            end2 = res.find(' <br', start)
            if ((end2 > start) and (end2 < end)): end = end2
            newfilenames.append(res[start+offset: end])
            this_title_num+=1

        # Allow the user to select which title he/she would like
        if (this_title_num != 0):
          print 'Top ' + str(this_title_num) + ' Matching movie titles ..........'
          for i in range(this_title_num):
            print '  Choice ' + str(i+1) + ' : ' + newfilenames[i]
          print 'Select the movie title you would like (enter ' + str(this_title_num+1) + \
                ' or above to select none of them)'
          Choice = '0'
          while (type(Choice) != int):
            try:
              Choice = int(raw_input())
            except KeyboardInterrupt:
              sys.exit()
            except:
              print 'That is not a valid input. You must input a number between 0 and 9'

          # Now that we have the proper choice, prompt the user one more time to make sure
          # he or she wishes to make the move
          if ((Choice > 0) and (Choice <= this_title_num) and (this_title_num != 0)):
            newfilename = newfilenames[Choice-1]
            # Rename the file after replacing bad characters
            newfilename = newfilename.replace(': ', '-')
            newpath = os.path.join(rootdir, directory, newfilename+extension)
            print ''
            print 'Old file path is      : ' + oldpath
            print 'New file path will be : ' + newpath
            print ''
            print 'Would you like to rename the file? Press 1 for yes: any other number to skip...'
            Choice = '0'
            while (type(Choice) != int):
              try:
                Choice = int(raw_input())
              except KeyboardInterrupt:
                sys.exit()
              except:
                print 'That is not a valid input. You must input a number between 0 and 9'
            if (Choice == 1):
              print ''
              print 'Renaming ' + oldpath + ' to ' + newpath
              print ''
              os.rename(oldpath, newpath)
            else: 
              print ''
              print 'Skipping...'
          else:
            print 'A valid choice was not selected. Skipping...'

        else:
          print 'No matching IMDB entry! Moving to next subdirectory...'
        
    # NO: we are skipping this directory 
    else:
      print 'Skipping directory...'
      print ''
