# -*- coding: utf-8 -*-
from django.contrib import admin
from polymorphic.admin import PolymorphicChildModelAdmin

from coin.offers.models import Offer, OfferSubscription
from coin.offers.offersubscription_filter import\
            OfferSubscriptionTerminationFilter,\
            OfferSubscriptionCommitmentFilter
from coin.resources.models import IPSubnet
import autocomplete_light


class IPSubnetInline(admin.TabularInline):
    model = IPSubnet
    extra = 0


class OfferAdmin(admin.ModelAdmin):
    list_display = ('configuration_type', 'name', 'billing_period', 'period_fees',
                    'initial_fees')
    list_display_links = ('name',)
    list_filter = ('configuration_type',)
    search_fields = ['name']

    # def get_readonly_fields(self, request, obj=None):
    #     if obj:
    #         return ['backend',]
    #     else:
    #         return []


class OfferSubscriptionAdmin(admin.ModelAdmin):
    list_display = ('member', 'offer', 'subscription_date', 'commitment',
                    'resign_date')
    list_display_links = ('member','offer')
    list_filter = ( OfferSubscriptionTerminationFilter,
                    OfferSubscriptionCommitmentFilter,
                    'member', 'offer')
    search_fields = ['member__first_name', 'member__last_name', 'member__email']
    
    fields = (
                'member',
                'offer',
                'subscription_date',
                'commitment',
                'resign_date'
             )
    form = autocomplete_light.modelform_factory(OfferSubscription)

    inlines = [ IPSubnetInline ]

    def get_inline_instances(self, request, obj=None):
        """
        Si en edition, alors affiche en inline le formulaire de la configuration
        correspondant à l'offre choisie
        """
        ipsubnet_inline = [IPSubnetInline(self.model, self.admin_site)]

        if obj is not None:
            for item in PolymorphicChildModelAdmin.__subclasses__():
                if (item.base_model.__name__ == obj.offer.configuration_type):
                    return [item.inline(self.model, self.admin_site)] + ipsubnet_inline
        return ipsubnet_inline

admin.site.register(Offer, OfferAdmin)
admin.site.register(OfferSubscription, OfferSubscriptionAdmin)
