# -*- coding: utf-8 -*-
from django import forms
from django.contrib import admin
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.conf.urls import url

from coin.filtering_queryset import LimitedAdminInlineMixin
from coin.billing.models import Invoice, InvoiceDetail, Payment
from coin.billing.utils import get_invoice_from_id_or_number
from coin.offers.models import OfferSubscription
import autocomplete_light


class InvoiceDetailInline(LimitedAdminInlineMixin, admin.StackedInline):
    model = InvoiceDetail
    extra = 0
    fields = (('label', 'amount', 'quantity', 'tax'),
        ('offersubscription','period_from', 'period_to'))

    def get_filters(self, obj):
        """
        Le champ "Abonnement" est filtré afin de n'afficher que les abonnements
        du membre choisi dans la facture. Si pas de membre alors renvoi
        une liste vide
        """
        if obj and obj.member:
            return (('offersubscription', {'member':obj.member}),)
        else:
            return (('offersubscription', None),)

    def get_readonly_fields(self, request, obj=None):
        if not obj or not obj.member:
            return self.readonly_fields + ('offersubscription',)
        return self.readonly_fields


class PaymentInline(admin.StackedInline):
    model = Payment
    extra = 0
    fields = (('date', 'payment_mean', 'amount'),)


class InvoiceAdmin(admin.ModelAdmin):
    list_display = ('number', 'date', 'status', 'amount', 'member', 'is_validated')
    list_display_links = ('number', 'date')
    inlines = [InvoiceDetailInline, PaymentInline]
    fields = (('number', 'date', 'status'),
       ('date_due'),
       ('member'),
       ('amount','amount_paid'),
       ('is_validated', 'pdf'))
    readonly_fields = ('amount','amount_paid','is_validated','pdf')
    form = autocomplete_light.modelform_factory(Invoice)

    def get_formsets(self, request, obj=None):
        """
        Lorsque l'on est en création d'objet (obj=None) alors ne renvoi pas les
        formsets des inlines.
        Cela permet de ne pas afficher les champs détails de facture et paiement
        tant que la facture n'a pas été enregistré.
        Cette subtilité permet de s'assurer que le select "Abonnement" de
        InvoiceDetail est bien filtré avec le member de la facture
        """
        if obj:
            for _ in super(InvoiceAdmin, self).get_formsets(request, obj):
                yield _
        else:
            pass

    def get_urls(self):
        urls = super(InvoiceAdmin, self).get_urls()
        my_urls = [
            url(r'^validate/(?P<id>.+)$', self.admin_site.admin_view(self.validate_view), name='invoice_validate'),
        ]
        return my_urls + urls

    def validate_view(self, request, id):
        if request.user.is_superuser:
            invoice = get_invoice_from_id_or_number(id)
            invoice.validate()
            messages.success(request, 'La facture a été validée.')
        else:
            messages.error(request, 'Vous n\'avez pas l\'autorisation de valider une facture.')

        return HttpResponseRedirect(request.META["HTTP_REFERER"])

admin.site.register(Invoice, InvoiceAdmin)
