# -*- coding: utf-8 -*-

from django.forms import ModelForm, ValidationError
from django.db.models import Q

from coin.offers.models import OfferSubscription
from coin.configuration.models import Configuration


class ConfigurationForm(ModelForm):

    class Meta:
        model = Configuration
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        """
        This filter the offersubscription select field in configurations forms
        to only display subscription that are the sames type of actual configuration
        and that haven't already a configuration associated with
        """
        super(ConfigurationForm, self).__init__(*args, **kwargs)
        if self.instance:
            queryset = OfferSubscription.objects.filter(
                Q(offer__configuration_type=self.instance.model_name) & (
                Q(configuration=None) | Q(configuration=self.instance.pk)))
            self.fields['offersubscription'].queryset = queryset

    def clean_offersubscription(self):
        """
        This check if the selected administrative subscription is linked to an
        offer which use the same configuration type than the edited configuration.
        """
        offersubscription = self.cleaned_data['offersubscription']
        if offersubscription.offer.configuration_type != self.instance.model_name():
            raise ValidationError('Administrative subscription must refer an offer having a "{}" configuration type.'.format(self.instance.model_name()))

        return offersubscription