from io import BytesIO

from taggit.models import Tag
from xhtml2pdf import pisa

from django.http import HttpResponse, JsonResponse, HttpResponseServerError
from django.utils import timezone
from django.utils.text import slugify


def render_to_pdf(html):
    src = BytesIO(html.encode("ISO-8859-1"))
    dest = BytesIO()

    pdf = pisa.pisaDocument(src, dest)

    if not pdf.err:
        return HttpResponse(dest.getvalue(), content_type="application/pdf")

    return None


def slug_calc(request):
    """
    Ajax function that is called to calculate a slug from the title
    """
    if request.method == "GET":
        get = request.GET.copy()
        title = get["title"]
        slug_str = get["slug"]

        if not slug_str:
            date_str = timezone.now().strftime("%Y-%m-%d")
            slug_str = slugify(date_str) + "-" + slugify(title)

        return HttpResponse(slug_str)

    return HttpResponseServerError("Requires a title field.")


def tag_complete(request):
    """
    Ajax function that returns autocomplete suggestions for a given tag input
    """
    if request.method == "GET":
        get = request.GET.copy()
        term = get["term"]

        tag_objects = Tag.objects.filter(name__istartswith=term)

        tag_array = []
        for elem in tag_objects:
            tag_array.append(elem.name)

        return JsonResponse(tag_array, safe=False)

    return HttpResponseServerError("Requires a term field.")
