# barbacompta - invoicing for dummies
# Copyright (C) 2019-2020 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


from django.contrib import admin
from django.contrib.contenttypes.admin import GenericStackedInline
from django.db.models import F, Q, Sum

from .. import actions
from .. import admin as eo_gestion_admin
from ..eo_facture.admin import PaymentInline
from ..eo_facture.templatetags.eo_facture import amountformat
from . import models


class CommentaireInlineAdmin(GenericStackedInline):
    model = models.Commentaire
    ordering = ['-creation']
    extra = 0


class MontantAffecteFilter(admin.SimpleListFilter):
    title = 'Totalement affecté'
    parameter_name = 'montant_affecte'

    def lookups(self, request, model_admin):
        return [
            ('yes', 'Oui'),
            ('no', 'Non'),
        ]

    def queryset(self, request, queryset):
        qs = queryset.filter(montant__gt=0)
        qs = qs.annotate(montant_affecte=Sum('payments__montant_affecte'))
        if self.value() == 'no':
            return qs.filter(Q(montant__gt=F('montant_affecte')) | Q(payments__isnull=True))
        if self.value() == 'yes':
            return qs.filter(montant__lte=F('montant_affecte'))


class LigneBanquePopAdmin(admin.ModelAdmin):
    search_fields = ['montant', 'reference', 'libelle']
    inlines = [PaymentInline, CommentaireInlineAdmin]
    list_display = ['date_valeur', 'libelle', 'column_montant', 'column_montant_non_affecte']
    readonly_fields = [
        'compte',
        'date_comptabilisation',
        'date_valeur',
        'libelle',
        'reference',
        'date_operation',
        'montant',
        'montant_non_affecte',
    ]
    date_hierarchy = 'date_valeur'
    ordering = ['-date_valeur']
    actions = [actions.export_as_csv]
    list_filter = (MontantAffecteFilter,)

    def column_montant(self, obj):
        return amountformat(obj.montant)

    column_montant.short_description = 'Montant'

    def column_montant_non_affecte(self, obj):
        return amountformat(obj.montant_non_affecte())

    column_montant_non_affecte.short_description = 'Montant non affecté'

    def lookup_allowed(self, *args, **kwargs):
        return True

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        qs = qs.prefetch_related("payments")
        return qs

    def has_add_permission(self, request):
        return False


admin.site.register(models.LigneBanquePop, LigneBanquePopAdmin)
admin.site.register(models.SoldeBanquePop, list_display=['compte', 'date', 'montant'])

eo_gestion_admin.site.register(models.LigneBanquePop, LigneBanquePopAdmin)
eo_gestion_admin.site.register(models.SoldeBanquePop, list_display=['compte', 'date', 'montant'])
eo_gestion_admin.site.register(models.Commentaire)
