from django.core.management.base import BaseCommand, CommandError
import csv

def attr(name):
    return lambda x: getattr(x, name)

def meth(name):
    return lambda x: attr(name)()

def sched_attr(name):
    def foo(x):
        s = x.scheduledevent_set.all()[0]
        return unicode(getattr(s, name))
    return foo

FIELDS = [
    ('id', attr('id')),
    ('title', attr('title')),
    ('start', sched_attr('start')),
    ('duration', attr('duration')),
    ('room', sched_attr('room')),
    ('speakers', attr('presenters_listing')),
    ('summary', attr('summary'))
    ]

class Command(BaseCommand):
    args = '<filename>'

    def handle(self, *args, **options):
        from django.db import models
        from pycon.core import safe_ascii_encode
        if len(args) != 1:
            raise CommandError('give a filename')

        try:
            models = models.get_app('schedule')
        except (ImproperlyConfigured, ImportError), e:
            raise CommandError(
                "%s. Are you sure your INSTALLED_APPS setting is correct?" % e)

        f = file(args[0],'w')
        csvf = csv.writer(f)
        events = models.Event.objects.filter(type__in=['P','S','T','E']).order_by('id')
        csvf.writerow([x[0] for x in FIELDS])

        for e in events:
            csvf.writerow([ safe_ascii_encode(c[1](e)) for c in FIELDS])
