import csv
import datetime
from cStringIO import StringIO
from django.http import HttpResponse
from signet.canvas.models import Submission

@login_required
def ftype_batch(request, ftype):
    cv_id = FTYPE_SETS[ftype]['cv'].id
    return run_batch(fname_pre=ftype,
                     qs=Submission.objects.filter(responder__id=1,
                                                  chart__id=cv_id,
                                                  submit_date__isnull=True))

def run_batch(fname_pre, qs):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(mimetype='text/csv')
    sd = datetime.datetime.now()
    fname = '%s-%s.csv' % (fname_pre, sd.strftime('%Y%m%d-%H%M-%s'))
    response['Content-Disposition'] = 'attachment; filename=%s' % fname
    response._container = write_batch(qs, sd)
    response._is_string = False

    return response

def write_batch(qs, d):
    i = 0
    sf = StringIO()
    writer = csv.writer(sf, quoting=csv.QUOTE_NONE)
    for s in qs:
        print 'Row #%d' % (i + 1,)
        #Clear contents so we don't return duplicate rows (and conserve memory)
        sf.truncate(0)
        s_responses = s.responses()
        srk = sorted(s_responses.keys())
        row = [repr(s_responses[k]).strip() for k in srk]

        writer.writerow(row)
        s.submit_date = d
        s.save()
        i += 1
        yield sf.getvalue()