import random
from django.db import models, IntegrityError
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from django_lcore.core import LcoreUserProfileMethods, setup_sync_hooks, VPN_AUTH_STORAGE

from payments.models import BaseSubUser

prng = random.SystemRandom()


def random_gift_code():
    charset = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ"
    return ''.join([prng.choice(charset) for n in range(10)])


class VPNUser(models.Model, BaseSubUser, LcoreUserProfileMethods):
    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)
    last_vpn_auth_fail_notice = models.DateTimeField(blank=True, null=True)
    notify_expiration = models.BooleanField(default=True)
    notify_vpn_auth_fail = models.BooleanField(default=True)

    trial_periods_given = models.IntegerField(default=0)

    last_vpn_auth = models.DateTimeField(blank=True, null=True)
    last_core_sync = 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)

    def clear_fields(self):
        self.expiration = None
        self.last_expiry_notice = None
        self.last_vpn_auth = None
        self.last_core_sync = None
        self.referrer = None
        self.referrer_used = False
        self.campaign = None

    def on_payment_confirmed(self, payment):
        if self.referrer and not self.referrer_used:
            self.referrer.vpnuser.add_paid_months(1, 'referrer', f"rewarded for {self.user.username} (payment #{payment.id})")
            self.referrer.vpnuser.save()
            self.referrer_used = True
            self.save()

    def lcore_sync(self):
        if VPN_AUTH_STORAGE == 'inst':
            return
        from lambdainst.tasks import push_user
        push_user.delay(user_id=self.user.id)

    def notify_payment(self, payment):
        return

    def notify_subscription(self, sub):
        return

    def notify_refund(self, payment):
        return

    def __str__(self):
        return self.user.username

setup_sync_hooks(User, VPNUser)

#from django.db.models.signals import post_save
#from django.dispatch import receiver
#@receiver(post_save, sender=User)
#def create_vpnuser(sender, instance, created, **kwargs):
#    if created:
#        try:
#            VPNUser.objects.create(user=instance)
#        except IntegrityError:
#            pass
