# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render, render_to_response
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
from coin.billing.utils import get_invoice_from_id_or_number

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
    """

    invoice = get_invoice_from_id_or_number(id)

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

    pdf = render_as_pdf('billing/invoice_pdf.html', {"invoice": invoice})

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

    response.write(pdf)

    return response

def invoice(request, id):
    """
    Affiche une facture et son détail
    id peut être soit la pk d'une facture, soit le numero de facture
    """
    invoice = get_invoice_from_id_or_number(id)

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

    return render_to_response('billing/invoice.html', {"invoice": invoice},
                              context_instance=RequestContext(request))

    return response



