# -*- coding: utf-8 -*-
import datetime
import calendar
import random
from decimal import Decimal
from django.db import models
from coin.offers.models import Offer
from coin.members.models import Member


class Invoice(models.Model):

    INVOICES_STATUS_CHOICES = (
        ('open', u'A payer'),
        ('closed', u'Reglée'),
        ('trouble', u'Litige')
    )

    number = models.CharField(max_length=25,
                              default=lambda:Invoice.next_invoice_number(),
                              unique=True,
                              verbose_name='Numéro')
    status = models.CharField(max_length=50, choices=INVOICES_STATUS_CHOICES,
                              default='open',
                              verbose_name='Statut')
    date = models.DateField(default=datetime.date.today, null=True)
    period_from = models.DateField(
        default=datetime.date(datetime.date.today().year,
                              datetime.date.today().month, 1),
        null=True,
        verbose_name=u'Début de période de facturation')
    period_to = models.DateField(
        default=(datetime.date(datetime.date.today().year,
                               datetime.date.today().month + 1, 1) -
                 datetime.timedelta(days=1)),
        null=True,
        verbose_name=u'Fin de période de facturation')
    date_due = models.DateField(
        default=(datetime.date(datetime.date.today().year,
                               datetime.date.today().month + 1, 1) -
                 datetime.timedelta(days=1)),
        null=True,
        verbose_name=u'Date d\'échéance de paiement')
    member = models.ForeignKey(Member, null=True, blank=True, default=None,
                               verbose_name='Membre')

    def amount(self):
      "Calcul le montant de la facture en fonction des éléments de détails"
      total = Decimal('0.0')
      for detail in self.details.all():
        total += detail.amount * (detail.tax / Decimal('100.0') + Decimal('1.0'))
      return total.quantize(Decimal('0.01'))

    @staticmethod
    def next_invoice_number():
      "Détermine un numéro de facture aléatoire"
      return u'%s%02i-%i-%i' % (datetime.date.today().year,
                                datetime.date.today().month,
                                random.randrange(100, 999),
                                random.randrange(100, 999))

    def __unicode__(self):
        return u'#%s %0.2f€ %s' % (self.number, self.amount(), self.date_due)

    class Meta:
        verbose_name = 'facture'


class InvoiceDetail(models.Model):

    label = models.CharField(max_length=100)
    amount = models.DecimalField(max_digits=5, decimal_places=2,
                                 verbose_name='Montant')
    quantity = models.IntegerField(null=True, verbose_name=u'Quantité',
                                   default=1)
    tax = models.DecimalField(null=True, default=0.0, decimal_places=2,
                              max_digits=4, verbose_name='TVA',
                              help_text='en %')
    invoice = models.ForeignKey(Invoice, verbose_name='Facture',
                                related_name='details')
    offer = models.ForeignKey(Offer, null=True, blank=True, default=None,
                              verbose_name='Offre')

    def __unicode__(self):
        return self.label

    class Meta:
        verbose_name = 'détail de facture'


class Payment(models.Model):

    PAYMENT_MEAN_CHOICES = (
        ('cash', u'Espèces'),
        ('check', u'Chèque'),
        ('transfer', u'Virement'),
        ('other', u'Autre')
    )

    payment_mean = models.CharField(max_length=100, null=True,
                                    default='transfer',
                                    choices=PAYMENT_MEAN_CHOICES,
                                    verbose_name='Moyen de paiement')
    amount = models.DecimalField(max_digits=7, decimal_places=2, null=True,
                                 verbose_name='Montant')
    date = models.DateField(default=datetime.date.today)
    invoce = models.ForeignKey(Invoice, verbose_name='Facture')

    class Meta:
        verbose_name = 'paiement'
