# Path: ccvpn/common.py
# def parse_integer_list(ls):
#     l = ls.split(',')
#     l = [p.strip() for p in l]
#     l = [p for p in l if p]
#     l = [int(p) for p in l]
#     return l
# 
# Path: lambdainst/models.py
# class VPNUser(models.Model):
#     class Meta:
#         verbose_name = _("VPN User")
#         verbose_name_plural = _("VPN Users")
# 
#     user = models.OneToOneField(User, on_delete=models.CASCADE)
#     notes = models.TextField(blank=True)
# 
#     expiration = models.DateTimeField(blank=True, null=True)
#     last_expiry_notice = models.DateTimeField(blank=True, null=True)
#     notify_expiration = models.BooleanField(default=True)
# 
#     trial_periods_given = models.IntegerField(default=0)
# 
#     last_vpn_auth = models.DateTimeField(blank=True, null=True)
# 
#     referrer = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL,
#                                  related_name='referrals')
#     referrer_used = models.BooleanField(default=False)
#     campaign = models.CharField(blank=True, null=True, max_length=64)
# 
#     @property
#     def is_paid(self):
#         if self.get_subscription():
#             return True
#         if not self.expiration:
#             return False
#         return self.expiration > timezone.now()
# 
#     @property
#     def time_left(self):
#         return timezone.now() - self.expiration
# 
#     def add_paid_time(self, time):
#         now = timezone.now()
#         if not self.expiration or self.expiration < now:
#             self.expiration = now
#         self.expiration += time
# 
#         # Propagate update to core
#         if core.VPN_AUTH_STORAGE == 'core':
#             core.update_user_expiration(self.user)
# 
#     def give_trial_period(self):
#         self.add_paid_time(get_trial_period_duration())
#         self.trial_periods_given += 1
# 
#     @property
#     def can_have_trial(self):
#         if self.trial_periods_given >= site_config.TRIAL_PERIOD_MAX:
#             return False
#         if self.user.payment_set.filter(status='confirmed').count() > 0:
#             return False
#         return True
# 
#     @property
#     def remaining_trial_periods(self):
#         return site_config.TRIAL_PERIOD_MAX - self.trial_periods_given
# 
#     def on_payment_confirmed(self, payment):
#         if self.referrer and not self.referrer_used:
#             self.referrer.vpnuser.add_paid_time(timedelta(days=14))
#             self.referrer.vpnuser.save()
#             self.referrer_used = True
# 
#     def get_subscription(self, include_unconfirmed=False):
#         """ Tries to get the active (and most recent) Subscription """
#         s = Subscription.objects.filter(user=self.user, status='active') \
#                                 .order_by('-id') \
#                                 .first()
#         if s is not None or include_unconfirmed is False:
#             return s
#         s = Subscription.objects.filter(user=self.user, status='unconfirmed') \
#                                 .order_by('-id') \
#                                 .first()
#         return s
# 
#     def __str__(self):
#         return self.user.username


from django.core.management.base import BaseCommand
from datetime import timedelta
from django.db.models import Q, F
from django.conf import settings
from django.utils import timezone
from django.template.loader import get_template
from django.core.mail import send_mass_mail
from constance import config as site_config
from ccvpn.common import parse_integer_list
from lambdainst.models import VPNUser



ROOT_URL = settings.ROOT_URL
SITE_NAME = settings.TICKETS_SITE_NAME


def get_next_expirations(days=3):
    """ Gets users whose subscription will expire in some days """

    limit_date = timezone.now() + timedelta(days=days)

    users = VPNUser.objects.exclude(user__email__exact='')

    users = users.filter(expiration__gt=timezone.now())  # Not expired
    users = users.filter(expiration__lt=limit_date)  # Expire in a few days

    # Make sure we dont send the notice twice
    users = users.filter(Q(last_expiry_notice__isnull=True)
                         | Q(expiration__gt=F('last_expiry_notice')
                             + timedelta(days=days)))
    return users


class Command(BaseCommand):
    help = "Notify users near the end of their subscription"

    def handle(self, *args, **options):
        from_email = settings.DEFAULT_FROM_EMAIL


# Path: ccvpn/common.py
# def parse_integer_list(ls):
#     l = ls.split(',')
#     l = [p.strip() for p in l]
#     l = [p for p in l if p]
#     l = [int(p) for p in l]
#     return l
# 
# Path: lambdainst/models.py
# class VPNUser(models.Model):
#     class Meta:
#         verbose_name = _("VPN User")
#         verbose_name_plural = _("VPN Users")
# 
#     user = models.OneToOneField(User, on_delete=models.CASCADE)
#     notes = models.TextField(blank=True)
# 
#     expiration = models.DateTimeField(blank=True, null=True)
#     last_expiry_notice = models.DateTimeField(blank=True, null=True)
#     notify_expiration = models.BooleanField(default=True)
# 
#     trial_periods_given = models.IntegerField(default=0)
# 
#     last_vpn_auth = models.DateTimeField(blank=True, null=True)
# 
#     referrer = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL,
#                                  related_name='referrals')
#     referrer_used = models.BooleanField(default=False)
#     campaign = models.CharField(blank=True, null=True, max_length=64)
# 
#     @property
#     def is_paid(self):
#         if self.get_subscription():
#             return True
#         if not self.expiration:
#             return False
#         return self.expiration > timezone.now()
# 
#     @property
#     def time_left(self):
#         return timezone.now() - self.expiration
# 
#     def add_paid_time(self, time):
#         now = timezone.now()
#         if not self.expiration or self.expiration < now:
#             self.expiration = now
#         self.expiration += time
# 
#         # Propagate update to core
#         if core.VPN_AUTH_STORAGE == 'core':
#             core.update_user_expiration(self.user)
# 
#     def give_trial_period(self):
#         self.add_paid_time(get_trial_period_duration())
#         self.trial_periods_given += 1
# 
#     @property
#     def can_have_trial(self):
#         if self.trial_periods_given >= site_config.TRIAL_PERIOD_MAX:
#             return False
#         if self.user.payment_set.filter(status='confirmed').count() > 0:
#             return False
#         return True
# 
#     @property
#     def remaining_trial_periods(self):
#         return site_config.TRIAL_PERIOD_MAX - self.trial_periods_given
# 
#     def on_payment_confirmed(self, payment):
#         if self.referrer and not self.referrer_used:
#             self.referrer.vpnuser.add_paid_time(timedelta(days=14))
#             self.referrer.vpnuser.save()
#             self.referrer_used = True
# 
#     def get_subscription(self, include_unconfirmed=False):
#         """ Tries to get the active (and most recent) Subscription """
#         s = Subscription.objects.filter(user=self.user, status='active') \
#                                 .order_by('-id') \
#                                 .first()
#         if s is not None or include_unconfirmed is False:
#             return s
#         s = Subscription.objects.filter(user=self.user, status='unconfirmed') \
#                                 .order_by('-id') \
#                                 .first()
#         return s
# 
#     def __str__(self):
#         return self.user.username


# Path: lambdainst/management/commands/expire_notify.py
from django.core.management.base import BaseCommand
from datetime import timedelta
from django.db.models import Q, F
from django.conf import settings
from django.utils import timezone
from django.template.loader import get_template
from django.core.mail import send_mass_mail
from constance import config as site_config
from ccvpn.common import parse_integer_list
from lambdainst.models import VPNUser




ROOT_URL = settings.ROOT_URL
SITE_NAME = settings.TICKETS_SITE_NAME


def get_next_expirations(days=3):
    """ Gets users whose subscription will expire in some days """

    limit_date = timezone.now() + timedelta(days=days)

    users = VPNUser.objects.exclude(user__email__exact='')

    users = users.filter(expiration__gt=timezone.now())  # Not expired
    users = users.filter(expiration__lt=limit_date)  # Expire in a few days

    # Make sure we dont send the notice twice
    users = users.filter(Q(last_expiry_notice__isnull=True)
                         | Q(expiration__gt=F('last_expiry_notice')
                             + timedelta(days=days)))
    return users


class Command(BaseCommand):
    help = "Notify users near the end of their subscription"

    def handle(self, *args, **options):
        from_email = settings.DEFAULT_FROM_EMAIL


        for v in parse_integer_list(site_config.NOTIFY_DAYS_BEFORE):