# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.contrib import admin
from polymorphic.admin import PolymorphicParentModelAdmin, PolymorphicChildModelAdmin

from coin.resources.models import IPSubnet
from coin.configuration.models import Configuration
from coin.configuration.forms import ConfigurationForm

"""
Implementation note : When creating child admin class, you have to inherit
ConfigurationAdminFormMixin. This make use of ConfigurationForm form that
filter offersubscription select input to avoid selecting wrong subscription.
"""

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


class ParentConfigurationAdmin(PolymorphicParentModelAdmin):
    base_model = Configuration
    polymorphic_list = True
    list_display = ('model_name','configuration_type_name', 'offersubscription', 'offer_subscription_member')

    def offer_subscription_member(self, config):
        return config.offersubscription.member
    offer_subscription_member.short_description = 'Membre'

    def get_child_models(self):
        """
        Renvoi la liste des modèles enfants de Configuration
        ex :((VPNConfiguration, VPNConfigurationAdmin),
            (ADSLConfiguration, ADSLConfigurationAdmin))
        """
        return (tuple((x.base_model, x) for x in PolymorphicChildModelAdmin.__subclasses__()))

    def get_urls(self):
        """
        Fix a django-polymorphic bug that randomly set wrong url for a child
        model in admin.
        This remove somes dummy urls that have not to be returned by the parent model
        https://github.com/chrisglass/django_polymorphic/issues/105
        """
        urls = super(ParentConfigurationAdmin, self).get_urls()
        for model, _ in self.get_child_models():
            admin = self._get_real_admin_by_model(model)
            for admin_url in admin.get_urls():
                for url in urls:
                    if url.name == admin_url.name:
                        urls.remove(url)
        return urls


class ConfigurationAdminFormMixin(object):
    base_form = ConfigurationForm

admin.site.register(Configuration, ParentConfigurationAdmin)
