# -*- coding: utf-8 -*-
import datetime
from dateutil.relativedelta import relativedelta
from django.http import HttpResponse
from django.db.models import Q
from coin.offers.models import Offer, OfferSubscription
from coin.members.models import Member
from coin.billing.models import Invoice, InvoiceDetail


def generate_missing_invoices(request):
	"""
	Pour chaque abonnement (OfferSubscription):
		Vérifie pour chaque période de facturation si elle a été facturée
		Sinon génère la facture correspondante
	"""
	members = Member.objects.filter(
		Q(offersubscription__resign_date__isnull=True) | Q(offersubscription__resign_date__gte=datetime.date.today()))
	offer_subscriptions = OfferSubscription.objects.filter(
		Q(resign_date__isnull=True) | Q(resign_date__gte=datetime.date.today()))
	sortie = ""
	for member in members:
		sortie += '<br /> %s - %s' % (member, 
			generate_invoice_for_a_period(member, datetime.date(2013,12,5)))

	return HttpResponse(sortie)


def generate_invoice_for_a_period(member, date):
	"""
	Génère si necessaire une facture pour un membre en prenant la date passée 
	en paramètre comme premier mois de période. Renvoi la facture générée
	ou Non si aucune facture n'était necessaire.
	"""
	invoice = None


	offer_subscriptions = OfferSubscription.objects.filter(
		Q(resign_date__isnull=True) | Q(resign_date__gte=datetime.date.today()),
		member__exact=member.pk)

	for offer_subscription in offer_subscriptions:
		offer = offer_subscription.offer

		invoice_test = Invoice.objects.filter(
			period_from__lte=date,
			period_to__gte=date,
			details__offer__exact=offer.pk,
			member__exact=member.pk)

		if not invoice_test.exists():			
			if invoice == None:
				invoice = Invoice.objects.create(
					period_from=datetime.date(date.year,date.month,1),
					period_to=datetime.date(date.year,date.month,1),
					date_due=datetime.date.today(),
					member=member
				)

			new_period_to = (datetime.date(date.year,date.month,1) +
							relativedelta(months = +offer.billing_period) -
							relativedelta(days = +1))
			if new_period_to > invoice.period_to:
				invoice.period_to=new_period_to
			
			invoice.details.create(label=offer.name,
				amount=offer.period_fees,
				offer=offer)
			print invoice.period_to
			invoice.save();

	return invoice
