# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
from django.core.exceptions import PermissionDenied
from coin.billing.models import Invoice
from coin.members.models import Member
from coin.html2pdf import render_as_pdf
from coin.billing.create_subscriptions_invoices import create_all_members_invoices_for_a_period

def gen_invoices(request):
    create_all_members_invoices_for_a_period()
    return HttpResponse('blop')

def invoice_pdf(request, id):
    """
    Renvoi une facture générée en format pdf
    id peut être soit la pk d'une facture, soit le numero de facture
    """
    try:
        invoice = Invoice.objects.get(pk=id)
    except:
        invoice = get_object_or_404(Invoice, number=id)

    if not invoice.has_owner(request.user.username)\
       and not request.user.is_superuser:
        raise PermissionDenied

    member = invoice.member

    context = {"invoice": invoice, 'member': member}

    pdf = render_as_pdf('billing/invoice.html', context)

    response = HttpResponse(content_type='application/pdf')
    #response['Content-Disposition'] = 'attachment; filename="facture.pdf"'

    response.write(pdf)

    return response
