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

def room(x):
    f = sched_attr('room')
    return f(x).split()[-1]

def relattr(*names):
    def foo(x):
        for name in names:
            x = getattr(x, name)
        return unicode(x)
    return foo

def interest(anon=True, reg=True):
    def foo(x):
        if anon and reg:
            return str(x.selectedevent_set.filter(status=1).count())
        if anon:
            return str(x.selectedevent_set.filter(user__isnull=True, status=1).count())
        return str(x.selectedevent_set.filter(user__isnull=False, status=1).count())
    return foo

def ends(x):
    s = x.scheduledevent_set.all()[0]
    return str(bool(s.same_session_set[s.same_session_set.count()-1].event.id == x.id))[0]

def empty(x):
    return ''

def fixed(v):
    def foo(x):
        return v
    return foo

BASIC = [
    ('eid', attr('id')),
    ('tid', attr('proposal_id')),
    ('U',   interest(anon=False)),
    ('A',   interest(reg=False)),
    ('T',   interest())
]

FIELDS = [
    ('eid',   attr('id')),
    ('tid',   attr('proposal_id')),
    ('dur',   attr('duration')),
    ('room',  room),
    ('level', attr('level')),
    ('para',  empty),
    ('ends',  ends),
    ('C',     fixed('F')),
    ('ii: u', interest(anon=False)),
    ('ii: a', interest(reg=False)),
    ('ii',    interest()),
    ('ai: u', empty),
    ('ai: a', empty),
    ('ai',    empty),
    ('-1',    empty),
    ('0',     empty),
    ('+1',    empty),
    ('start', sched_attr('start')),
    ('title', attr('title')),
]

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)

        cols = FIELDS

        f = file(args[0],'w')
        csvf = csv.writer(f)
        exclude = [ e.id for e in models.Event.objects.all() if e.scheduledevent_set.count() == 0 ]

        events = models.Event.objects.filter(type='E', proposal__isnull=False).exclude(id__in=exclude).order_by('id')
        csvf.writerow([x[0] for x in cols])
        for e in events:
            csvf.writerow([ safe_ascii_encode(c[1](e)) for c in cols])
