# -*- coding: utf-8 -*-
import os
from django.conf import settings
from tempfile import NamedTemporaryFile
from xhtml2pdf import pisa
from django.template import loader, Context

# Convert HTML URIs to absolute system paths so xhtml2pdf can access
# those resources
def link_callback(uri, rel):
	sUrl = settings.STATIC_URL     # Typically /static/
	sRoot = settings.STATIC_ROOT   # Typically /home/userX/project_static/
	mUrl = settings.MEDIA_URL      # Typically /static/media/
	mRoot = settings.MEDIA_ROOT    # Typically /home/userX/project_static/media/

	# convert URIs to absolute system paths
	if uri.startswith(mUrl):
	    path = os.path.join(mRoot, uri.replace(mUrl, ""))
	elif uri.startswith(sUrl):
	    path = os.path.join(sRoot, uri.replace(sUrl, ""))
	# make sure that file exists
	if not os.path.isfile(path):
	        raise Exception(
	                'media URI must start with %s or %s' % \
	                (sUrl, mUrl))
	return path


def render_as_pdf(template, context):
	"""
	Génére le template donné avec les données du context donné en HTML et le
	converti en PDF via le module xhtml2pdf
	"""
	template = loader.get_template(template)
	html = template.render(Context(context))
	file = NamedTemporaryFile()

	pisaStatus = pisa.CreatePDF(html, dest=file, link_callback=link_callback)

	# Return PDF document through a Django HTTP response
	file.seek(0)
	pdf = file.read()
	file.close()

	return pdf
