from django.db import models
from django.conf import settings
from django.utils import timezone
from limitmonitor.models import get_available_bundles


class BundleChange(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    from_bdl = models.CharField(max_length=100)
    to_bdl = models.CharField(max_length=100)
    is_pending = models.BooleanField(default=True)
    pay_url = models.URLField(default='')
    new_order_id = models.CharField(max_length=100)
    old_subscription_id = models.CharField(max_length=100)
    created_date = models.DateTimeField(default=timezone.now)

    def is_family_downgrade(self):
        """Returns true if this BundleChange instance is a downgrade from a
        group bundle (Family pack) to a single bundle (Basic or
        Complete). Returns False otherwise."""

        bundles = get_available_bundles()
        from_bdl = bundles.get(self.from_bdl, None)
        to_bdl = bundles.get(self.to_bdl, None)
        if from_bdl and to_bdl:
            if (
                from_bdl.get('type', None) == 'GROUP'
                and (
                    to_bdl.get('type', None) == 'COMPLETE'
                    or to_bdl.get('type', None) == 'BASIC'
                )
            ):
                return True
        return False
