from django.contrib import admin

from .models import (
    Document, Cost, Good, CostUse, GoodUse, Service, ServiceUse)


@admin.register(Document)
class DocumentAdmin(admin.ModelAdmin):
    list_display = ('name', 'date', 'type')


class GoodUseInline(admin.TabularInline):
    model = GoodUse
    extra = 1


class CostUseInline(admin.TabularInline):
    model = CostUse
    extra = 1


class ServiceUseInline(admin.TabularInline):
    model = ServiceUse
    extra = 1
    fk_name = 'service'


class DirectDocumentFilter(admin.SimpleListFilter):
    title = 'Document'

    parameter_name = 'document'

    def queryset(self, request, queryset):
        document = self.value()
        if not document:
            return queryset
        else:
            return queryset.filter(document=document)

    def lookups(self, request, model_admin):
        for i in Document.objects.all():
            yield i.pk, str(i)


@admin.register(Cost)
class CostAdmin(admin.ModelAdmin):
    list_display = ('__str__', 'price', 'document')
    list_filter = [DirectDocumentFilter]


@admin.register(Good)
class GoodAdmin(admin.ModelAdmin):
    list_display = (
        '__str__', 'price', 'document',
        'provisioning_duration', 'monthly_provision')

    list_filter = [DirectDocumentFilter]


@admin.register(Service)
class ServiceAdmin(admin.ModelAdmin):
    list_display = (
        'name', 'subscriptions_count', 'document',
        'monthly_unit_cost', 'new_subscriber_cost')
    inlines = (CostUseInline, GoodUseInline, ServiceUseInline)
    list_filter = [DirectDocumentFilter]

    def monthly_unit_cost(self, obj):
        return '{:.2f}€'.format(obj.get_prices()['unit_recurring_price'])

    def new_subscriber_cost(self, obj):
        return '{:.2f}€'.format(obj.get_prices()['total_goods_value_share'])

    fieldsets = (
        (None, {
            'fields': (
                ('name', 'document'), 'description', 'subscriptions_count'),
        }),
        ('Ré-utilisabilité', {
            'fields': ('reusable',)
        })
    )
