# badges/views.py

from os import path
from cStringIO import StringIO

from django.contrib.auth.models import User
from django.http import HttpResponse

from dabo.dReportWriter import dReportWriter

def badge(request,user_id):
    
    # get some data
    ds = getds(user_id)

    # make the pdf
    pdf = mkpdf([ds])

    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=badge.pdf'
    
    response.write(pdf)
    return response

def getds(user_id):
    """
    Collect the data needed for a badge
    """

    user = User.objects.get(id=user_id)
    # up=user.get_profile()

    ds = {
    # 'full_name': unicode(user),
    'full_name': unicode(user).encode('utf-8'),
    'attendeeID': user.id+1000,
    # 'affiliation': up.affiliation,
    'affiliation': "%s Family"%user.last_name,
    'shirt_size': 'L',
    'shirt_back': True,
    'speaker': True,
    'vendor': True,
    'staff': True,
    }

    return ds
 
def mkpdf(ds):
    """
    Return a pdf made from the passed data 
    (and format file name? not this version)
    """
    # The images files referenced are relitive to the rfxml
    # so we need to figure out where we are
    # and make that part of the rfxml file name
    # which is currently in a dir below this one.
    codedir=path.dirname( __file__ )
    xmlfile="%s/registration_badge/badge.rfxml"%codedir

    # the pdf will be built in the buffer (no need for a disk file)
    buffer = StringIO()
    
    from reportlab.pdfbase import pdfmetrics 
    from reportlab.pdfbase.ttfonts import TTFont 
    pdfmetrics.registerFont(TTFont("FreeSans", "/usr/share/fonts/truetype/freefont/FreeSans.ttf")) 

    # generate the pdf in the buffer, using the layout and data
    rw = dReportWriter(OutputFile=buffer, ReportFormFile=xmlfile, Cursor=ds)
    rw.write()

    # get the pdf out of the buffer
    pdf = buffer.getvalue()
    buffer.close()

    return pdf

    
def test():
    from dabo.dReportWriter import dReportWriter
    from os import path

    ds = [{'first_name':'Carl', 'last_name':'Karsten', 'attendeeID':1234,
       'shirt_size':'L', 'shirt_back':True }]

    x = mkpdf(ds)
    return


# eof: badges/views.py

