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

STATUSMAP = {'a': 'A', 'r': 'D'}

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('Enter at least one appname.')

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

        f = file(args[0],'U')
        csvf = csv.reader(f)
        csvf.next()
        good = 0
        bad = 0
        for line in csvf:
            if len(line) != 5:
                continue
            if not all(line):
                continue
            try:
                talk = line[2]
                dur = int(line[3], 10)
                stat = STATUSMAP[line[4]]
            except:
                print "Bad Line:", line
                raise

            id = talk[:talk.find('.')]
            prop = models.Proposal.objects.get(pk=id)
            error = False
            if prop.duration != dur:
                print 'Talk:', talk, ' duration is', dur, 'in thunderdome, but', prop.duration, 'in system.'
                error = True

            if prop.status != stat:
                print 'Talk:', talk, 'status is', stat, 'in thunderdome, but', prop.status, 'in system.'
                error = True

            if error: bad += 1
            else: good += 1

        print "Verified", (good + bad), 'talks.'
        print "    found", good, "to match with system, and"
        print "    found", bad, "to have errors."
