"""Basic views for destinfo app"""

import cStringIO
import re

from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.template import RequestContext
from django.template.loader import render_to_string
from rlextra.rml2pdf import rml2pdf

from models import Poi


def make_pdf(rml):
    """
    Shortcut for creating pdf. If DEBUG is saves last rml and pdf to disk
    """
    if settings.DEBUG:
        rml2pdf._saveLastestRml(settings.SAVE_RML, rml) # pylint: disable-msg=W0212
    buf = cStringIO.StringIO()
    rml2pdf.go(rml, outputFileName=buf)
    buf.reset()
    pdf_data = buf.read()
    if settings.DEBUG:
        pdf_file = open(settings.SAVE_PDF, 'wb')
        pdf_file.write(pdf_data)
        pdf_file.close()
    return pdf_data

def poi2pdf(request, poi_id):
    """
    Used in admin to preview pdf.
    """

    poi = get_object_or_404(Poi, pk=poi_id)
    context = RequestContext(request, {
        'poi': poi
        })
    
    rml = render_to_string('rml/poi.rml', context).encode('utf-8')
    pdf_data = make_pdf(rml)
    response = HttpResponse(mimetype='application/pdf')
    response.write(pdf_data)
    response['Content-Disposition'] = 'attachment; filename=%s.pdf' % slugify(poi.name)

    return response


def slugify(value):
    """
    Normalizes string, converts to lowercase, removes non-alpha characters,
    and converts spaces to hyphens.
    """
    import unicodedata
    value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
    value = unicode(re.sub('[^\w\s-]', '', value).strip().lower())
    return re.sub('[-\s]+', '-', value)
