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

"""Various helpers designed to help configuration backends regarding
repetitive tasks."""

from django.core.exceptions import ValidationError
from django.db.models import Q

from coin.offers.models import OfferSubscription


class ValidateBackendType(object):
    """Helper validator for configuration backends.

    It ensures that the related subscription has the right backend
    type. This is a bit ugly, as validators are not meant for
    database-level sanity checks, but this is the cost of doing genericity
    the way we do.

    Note that this validator should not be needed for most cases, as the
    "limit_choices_to" parameter of the "administrative_subscription"
    OneToOneField should automatically limit the available choices on
    forms.  But it does not protect us if we fiddle manually with the
    database: better safe than sorry.
    """

    def __init__(self, backend_name):
        self.backend = backend_name

    def __call__(self, subscription):
        if OfferSubscription.objects.get(pk=subscription).offer.backend != self.backend:
            raise ValidationError('Administrative subscription must have a "{}" backend.'.format(self.backend))


def filter_subscriptions(backend_name, instance):
    """Helper function for configuration backends, allowing to filter
    subscriptions that have the right """
    return Q(offer__backend=backend_name) & (
        # Select "unassociated" subscriptions, plus our own
        # subscription (in case we are editing the object).
        Q((backend_name, None)) | Q((backend_name, instance.pk)))
