#!/usr/bin/python
# -*- coding: utf8 -*-
"""
This Python script is intended to fill the cast in the database 
This script is intended to be used by people that have an existing 
big video collection already in the database and want to fill
in the cast field. Perform movie data lookups using the
imdbpy.py script.

Written by William Stewart 2007
Based on find_meta.py by Pekka Jääskeläinen

"""

import sys
import optparse
import re
import os
import glob
import fileinput
import shlex
import socket
import urllib
import distutils.file_util
import imdbpy

try:
	from MythTV import MythDB, MythVideo
	mythdb = MythDB()
	mythvideo = MythVideo()
except:
	mythdb = None
	mythvideo = None

from stat import *

verbose=False

def print_verbose(string):
	global verbose
	if verbose:
		print string
	return

def main():
	global verbose

	usage = "usage: %prog [options]"

	p = optparse.OptionParser(usage=usage)
	p.add_option('--version', '-v', action="store_true", default=False,
		help="Display 1-line describing name, version, author etc.")

	options, arguments = p.parse_args()

	if options.version:
		print "MythVideo Cast Metadata Finder - William Stewart 2007"
		sys.exit(0)

	if not mythdb:
		print "Error can not access the mythtv database"
		sys.exit(1)

	c = mythdb.cursor()
	c.execute("""
		SELECT intid, filename, inetref
		FROM videometadata""")
	
	row = c.fetchone()
	while row is not None:
		intid = row[0]
		filename = row[1]
		imdb_id = row[2]
		if imdb_id != '00000000':
			meta = imdbpy.fetch_metadata(imdb_id)
			cast = meta.cast
			print "Found cast data for %s (%s)" % (filename, imdb_id) 
			mythvideo.setMetadata({'cast': cast}, intid)
		row = c.fetchone()
	c.close()

	sys.exit(0)

if __name__ == '__main__':
	main()
