#!/usr/bin/python
"""
EmailReminderSender.py - Send event email reminders
"""

from django.core.management import setup_environ
import settings
setup_environ(settings)

from datetime import datetime, timedelta
from Users.models import Reminder

def SendReminders(time, timeDescription, timeCode):
    """
    Send the emails for reminders that are due.
    """
    from django.template.loader import render_to_string

    checktime = datetime.now() + timedelta(seconds=time)
    associations = Reminder.objects.filter(event__eventtime__start__lt=checktime, assoctype=timeCode).distinct()
    for assoc in associations:
        recipient = recipient = ["\"%s\" <%s>" % (unicode(assoc.person), assoc.person.email)]
        sender = "MyPidge.com <thePidge@myPidge.com>"
        subject = "Reminder: %s" % (assoc.event.title)
        
        message = render_to_string('events-email-reminder', { 'user':  assoc.person, 'server_name': settings.SERVER_NAME, 'event': assoc.event, 'time_period': timeDescription })
        
        from django.core.mail import EmailMessage
        email = EmailMessage(subject=subject, from_email=sender, body=message, to=recipient)
        email.send()
        
        assoc.delete()

SendReminders(4500, 'about an hour', 'EML_HR')
SendReminders(60*60*24, 'one day', 'EML_DY')
