from django.core.management.base import NoArgsCommand
from django.template import RequestContext, Context, loader

class Command(NoArgsCommand):
    help = ''

    def handle_noargs(self, **options):
        from django.db import models
        from django.conf import settings
        from pycon.core import mail
        if not hasattr(settings, 'ATTREG_LISTING_TO'):
            raise CommandError(
                "Could not find ATTREG_LISTING_TO in settings.")
        if not hasattr(settings, 'ATTREG_LISTING_FROM_EMAIL'):
            raise CommandError(
                "Could not find ATTREG_LISTING_FROM_EMAIL in settings.")
        try:
            app = models.get_app('attendeereg')
        except (ImproperlyConfigured, ImportError), e:
            raise CommandError(
                "%s. Are you sure your INSTALLED_APPS setting is correct?" % e)


        print "loading template"
        t = loader.get_template("attendeereg/attendee_listing.txt")
        print "loading data"
        attendees = app.Registration.objects.filter(listing_ok=True,active=True)
        sessions = [ { 'name': name,
                       'tutorials': app.Tutorial.objects.filter(session=sess)}
                            for sess, name in app.SESSIONS ]
        c = { 'total': app.Registration.objects.filter(active=True).count(),
              'pending': app.Registration.objects.filter(
                    active=False, invoice__status__in=['CO', 'WA']).count(),
              'sessions': sessions,
              'attendees': attendees,
              'settings': settings}
        print "rendering"
        message = t.render(Context(c))
        if not settings.ATTREG_LISTING_FROM_EMAIL and settings.DEBUG:
            print message
            return
        print "sending messages"
        mail.send_mail(getattr(settings, 'CONFERENCE_NAME', '') +
                       ' Automatic Registration Report',
                       message, settings.ATTREG_LISTING_FROM_EMAIL,
                       settings.ATTREG_LISTING_TO,
                       replyto_email=getattr(settings,
                                    'ATTREG_LISTING_REPLYTO_EMAIL', None))
