# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render, render_to_response
from django.contrib import messages

from sendfile import sendfile

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, assert_user_can_view_the_invoice


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)

    assert_user_can_view_the_invoice(request, invoice)

    pdf_filename = 'Facture_%s.pdf' % invoice.number

    return sendfile(request, invoice.pdf.path,
                    attachment=True, attachment_filename=pdf_filename)


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)

    assert_user_can_view_the_invoice(request, invoice)

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

    return response
