#!/usr/bin/env python

import urllib, re, time, smtplib

URL = 'http://www.moviefone.com/showtimes/closesttheaters.adp?_action=setLocation&csz=94709'

tagpat = re.compile('<[^>]*>')
imgpat = re.compile('<img[^>]*alt="([^"]+)"[^>]*>')
parenpat = re.compile(r'\([^)]*\)')

def striptags(text):
    text = text.replace('&nbsp;', ' ').replace('<br>', '\n')
    text = imgpat.sub(r'\1', text)
    return tagpat.sub('', text).strip()

url = urllib.urlopen(URL)

theaters = []
movies = {}
showtimes = {}
hour, minute = time.localtime(time.time() - 7200)[3:5]
now = hour * 60 + minute
for line in url.readlines():
    if line.find('theater.adp') > 0:
        if line.find('page=map') < 0 and line.find('page=nearby') < 0:
            theater = striptags(line)
    if line.find('movie.adp') > 0:
        movielines = striptags(line).split('\n')
        movie = movielines[0]
        movie = parenpat.sub('', movie).strip()
        times = [t.strip() for t in movielines[-1].split('|') if t.strip()]
        for time in times:
            hour, minute = time.replace('am', '').replace('pm', '').split(':')
            hour, minute = int(hour), int(minute)
            if hour == 12:
                hour = 0
            dayminute = hour * 60 + minute
            if time.find('pm') > 0:
                dayminute += 12 * 60
            if now < dayminute < now + 120:
                if theater not in theaters:
                    theaters.append(theater)
                movies[theater] = movies.get(theater, []) + [movie]
                key = (theater, movie)
                showtimes[key] = showtimes.get(key, []) + [dayminute]

result = ''
for theater in theaters:
    result += '\n' + theater + ': '
    for movie in movies[theater]:
        result += movie
        times = []
        for dayminute in showtimes[(theater, movie)]:
            hour = dayminute / 60
            minute = dayminute % 60
            times.append('%02d:%02d' % (hour, minute))
        result += ' (%s) ' % ', '.join(times)

while result:
    server = smtplib.SMTP('mail.lfw.org')
    server.sendmail('p@p0.ca', '5106121824@mobile.att.net', result[:160])
    server.quit()
    result = result[140:].strip()

