from django.db import models
from django.conf import settings
from django.db.models.deletion import CASCADE
from django.shortcuts import reverse
from django.contrib.auth.models import User
from django.utils import timezone
from datetime import timedelta

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL,
                                on_delete=models.CASCADE, related_name='profile')
    # phone_number = models.CharField(max_length=20)
    country = models.CharField(max_length=200, blank=True, null=True, default="None")
    photo = models.ImageField(upload_to="profiles/", blank=True, null=True)
    signup_confirmation = models.BooleanField(default=False)
    ref_code = models.CharField(max_length=15, null=True, blank=True)
    recomended_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='ref_by')
    phone_number = models.CharField(max_length=20, blank=True, null=True)
    permanent_address = models.CharField(max_length=100, blank=True, null=True)
    present_address = models.CharField(max_length=100, blank=True, null=True)
    city = models.CharField(max_length=20, blank=True, null=True)
    postal_code = models.CharField(max_length=10, blank=True, null=True)
    dob = models.DateField(blank=True, null=True)
    two_factor_enabled = models.BooleanField(default=False)

    def __str__(self):
        return 'Profile for user {}'.format(self.user.username)

    def get_recommened_profiles(self):
        qs = Profile.objects.all()
        my_recs = []
        for profile in qs:
            try:
                if profile.recomended_by == self.user:
                    my_recs.append(profile)
            except Exception as e:
                pass
        return my_recs

    def getLink(self):
        return reverse("account:get_profile", kwargs={"ref_code": self.ref_code})

    def save(self, *args, **kwargs):
        if not self.ref_code:
            ref_code = self.user.username
            self.ref_code = ref_code
        super().save(*args, **kwargs)



class OTP(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    otp = models.CharField(max_length=6)
    created_at = models.DateTimeField(auto_now=True)

    def is_expired(self):
        return timezone.now() > self.created_at + timedelta(minutes=5)