#! /usr/local/bin/python

import sys, os, string, traceback, rfc822, cgi, time

homeDir = '/home/swdev'
themesDir = homeDir + os.sep + 'public_html/themes/templates'
if sys.platform == 'next':
	homeDir = '/datavol/src'
	themesDir = "/datavol/html/themes/templates"
pydir = homeDir + os.sep + 'pyscripts'
if os.uname()[1] == 'rackspace.swdev.com':
	pydir = '/usr/local/lib/swdevpy'
if not pydir in sys.path:
	sys.path.insert(0, pydir)
import moviesHandler, sendEmail, utils
import datepage, newsList

endl = os.linesep

leftNavHTML = "../leftNav.html"
moviesListingFilename = "movies.html"
movieRow = """<TR><TD VALIGN="TOP">%(title)s</TD>
	<TD VALIGN="TOP">%(times)s</TD></TR>"""
ticksFmt = '<br><font color="white">ticks: %d</font><br>'
msgSent = "<p><i>Your movie messages were sent to %s</i></p>"

def moviesListingPage(theatre, infoString='', themeDir=themesDir):
	html = ''
	rows = [ ]
	moviesTemplateFilename = themeDir + os.sep + moviesListingFilename
	moviesTemplate = open( moviesTemplateFilename ).read()
	theatreName = theatre.name
	moviesList = theatre.getMovies()
	pageDict = { 'theatreName': theatreName }
	pageDict['locale'] = theatre.locale
	pageDict['theatreKey'] = theatre.key
	timeTuple = time.localtime( time.time() )
	pageDict['datepage'] = datepage.flipStyleCalendar(timeTuple)
	pageDict['newsListSidebar'] = newsList.sidebar()
	for movie in theatre.movies:
		rowHTML = movieRow % movie
		rows.append(rowHTML)
	pageDict['rows'] = string.join(rows, os.linesep)
	pageDict['leftNav'] = open(leftNavHTML).read() 
	pageDict['info'] = infoString
	html = moviesTemplate % pageDict
	return html

theatresListingFilename = "theatres.html"
theatreRow = """
<TR>
	<TD VALIGN="TOP">
		<A HREF="movies.py?tk=%(theatreKey)s">%(theatreName)s</A> </TD>
	<TD VALIGN="TOP">
		<A HREF="mailto:allmovies@swdev.com?subject=%(theatreKey)s">%(theatreKey)s</A> </TD>
	</TR>
"""

def sendAsEmail(emailAddress, theatreKey, individually=1):
	mailFrom  = "Movies Demo<movies@swdev.com>"
	try:
		theatreKey = string.strip(theatreKey)
		result = moviesHandler.sendMovies(emailAddress, theatreKey, individually, 'web')
	except:
		tblines = traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback )
		msg = string.join(tblines, os.linesep)
		sendEmail.sendMsg( 'patrick@swdev.com', 'movies', msg, mailFrom )
	return None


def theatresListingPage(theatres, themeDir=themesDir):
	html = ''
	rows = [ ]
	theatresTemplateFilename = themeDir + os.sep + theatresListingFilename 
	theatresTemplate = open( theatresTemplateFilename ).read()
	for th in theatres.theatrekeys:
		theatre = theatres[th]
		rowHTML = theatreRow % theatre.data
		rows.append(rowHTML)
	rowsHTML = string.join(rows, os.linesep)
	pageDict = { 'rows': rowsHTML }
	pageDict['locale'] = theatre.locale
	pageDict['leftNav'] = open(leftNavHTML).read() 
	timeTuple = time.localtime( time.time() )
	pageDict['datepage'] = datepage.flipStyleCalendar(timeTuple)
	pageDict['newsListSidebar'] = newsList.sidebar()
	html = theatresTemplate % pageDict
	return html

def moviesMain(formData):

	fmt = ''
	theatreKey = ''
	if formData.has_key('tk'):
		theatreKey = formData['tk'].value
	locale='Portland'
	if formData.has_key('locale'):
		locale = formData['locale'].value
	emailAddress = ''
	if formData.has_key('to'):
		emailAddress = formData['to'].value
	if formData.has_key('fmt'):
		fmt = formData['fmt'].value

	userdata = utils.getCookieData()
	useragent = utils.getBrowserAgent()
	userdata['browser'] = useragent
	themedir = utils.getThemesDir(useragent)
	userdata['themedir'] = themedir

	# until i implement multiple browser support
	themedir = ''

	if theatreKey:
		theatres = moviesHandler.Theatres(locale='all')
		theatre = theatres[theatreKey]
		mailedMsg = ""
		if emailAddress:
			mailText = sendAsEmail(emailAddress, theatreKey)
			mailedMsg =  msgSent % emailAddress
		if fmt == 'xml':
			htmlOut = theatre.xml()
		else:
			htmlOut = moviesListingPage(theatre, mailedMsg)
	else:
		theatres = moviesHandler.Theatres(locale=locale)
		htmlOut = theatresListingPage(theatres)

	if fmt == 'xml':
		contentHeader = "Content-type: text/xml"
	else:
		contentHeader = utils.getAgentHeader(userdata['themedir'])
	cookieHeaders = utils.getCookiesString(userdata)

	if cookieHeaders:
		print cookieHeaders
	print contentHeader
	print endl
	print htmlOut

	
if __name__ == '__main__':

	starttime = time.clock()
	elapsed = 0
	formData = cgi.FieldStorage()
	try:
		moviesMain(formData)
	except:
		raise
	elapsed = time.clock() - starttime
	ticks = int(elapsed*100)
	print "<!-- ticks: %d -->" % ticks
	print ticksFmt % ticks