# Path: apps/core/models.py
# class EmailAuthToken(models.Model):
#     """
#     denotes single email auth token for an user
#     - tokenid:     unique token id
#     - user:        user object
#     - expire_time: expire time; < 24 hours
#     """
#     tokenid = models.CharField(max_length=48, primary_key=True)
#     user = models.ForeignKey(User, on_delete=models.CASCADE)
#     expire_time = models.DateTimeField()
# 
#     def __str__(self):
#         return f'{self.user} - {self.tokenid}'
# 
# class ResetPWToken(models.Model):
#     """
#     denotes single password reset token for an user
#     - tokenid:     unique token id
#     - user:        user object
#     - expire_time: expire time; < 24 hours
#     """
#     tokenid = models.CharField(max_length=48, primary_key=True)
#     user = models.ForeignKey(User, on_delete=models.CASCADE)
#     expire_time = models.DateTimeField()
# 
#     def __str__(self):
#         return f'{self.user} - {self.tokenid}'


import datetime
from secrets import token_hex
from django.conf import settings
from django.core.mail import send_mail
from django.utils import timezone
from apps.core.models import EmailAuthToken, ResetPWToken
    '<h3>SPARCS SSO 이메일 인증</h3>'
    '<p>안녕하세요, {name}님</p>'
    '<p>SPARCS SSO 계정에 대한 이메일 주소 변경 요청이 있었습니다.</p>'
    '<p>다음 링크를 클릭하거나 주소창에 붙여 넣어 이메일 {email}을 인증할 수 있습니다.</p>'
    '<p><a href="{link}">{link}</a></p>'
    '<p style="color:red"><b>만일 인증을 요청한 적이 없다면, '
    '절대로 링크를 클릭하지 마시고 sso.sysop@sparcs.org로 신고해주세요.</b></p>'
    '<br/>'
    '<h3>Verify your new email address</h3>'
    '<p>Hi, {name}</p>'
    '<p>You changed your email address for your SPARCS SSO account.</p>'
    '<p>To verify your new email {email}, click the link below:</p>'
    '<p><a href="{link}">{link}</a></p>'
    '<p style="color:red"><b>If you did not sign in, please DO NOT click '
    'the link and report us (sso.sysop@sparcs.org).</b></p>'
)

EMAIL_SENDER = 'noreply@sso.sparcs.org'


# issue reset pw token to user
def token_issue_reset_pw(user):
    ResetPWToken.objects.filter(user=user).delete()
    while True:
        tokenid = token_hex(24)
        if not ResetPWToken.objects.filter(tokenid=tokenid).count():
            break

    tomorrow = timezone.now() + datetime.timedelta(days=1)
    ResetPWToken.objects.filter(user=user).delete()

# Path: apps/core/models.py
# class EmailAuthToken(models.Model):
#     """
#     denotes single email auth token for an user
#     - tokenid:     unique token id
#     - user:        user object
#     - expire_time: expire time; < 24 hours
#     """
#     tokenid = models.CharField(max_length=48, primary_key=True)
#     user = models.ForeignKey(User, on_delete=models.CASCADE)
#     expire_time = models.DateTimeField()
# 
#     def __str__(self):
#         return f'{self.user} - {self.tokenid}'
# 
# class ResetPWToken(models.Model):
#     """
#     denotes single password reset token for an user
#     - tokenid:     unique token id
#     - user:        user object
#     - expire_time: expire time; < 24 hours
#     """
#     tokenid = models.CharField(max_length=48, primary_key=True)
#     user = models.ForeignKey(User, on_delete=models.CASCADE)
#     expire_time = models.DateTimeField()
# 
#     def __str__(self):
#         return f'{self.user} - {self.tokenid}'


# Path: apps/core/backends/token.py
import datetime
from secrets import token_hex
from django.conf import settings
from django.core.mail import send_mail
from django.utils import timezone
from apps.core.models import EmailAuthToken, ResetPWToken

    '<h3>SPARCS SSO 이메일 인증</h3>'
    '<p>안녕하세요, {name}님</p>'
    '<p>SPARCS SSO 계정에 대한 이메일 주소 변경 요청이 있었습니다.</p>'
    '<p>다음 링크를 클릭하거나 주소창에 붙여 넣어 이메일 {email}을 인증할 수 있습니다.</p>'
    '<p><a href="{link}">{link}</a></p>'
    '<p style="color:red"><b>만일 인증을 요청한 적이 없다면, '
    '절대로 링크를 클릭하지 마시고 sso.sysop@sparcs.org로 신고해주세요.</b></p>'
    '<br/>'
    '<h3>Verify your new email address</h3>'
    '<p>Hi, {name}</p>'
    '<p>You changed your email address for your SPARCS SSO account.</p>'
    '<p>To verify your new email {email}, click the link below:</p>'
    '<p><a href="{link}">{link}</a></p>'
    '<p style="color:red"><b>If you did not sign in, please DO NOT click '
    'the link and report us (sso.sysop@sparcs.org).</b></p>'
)

EMAIL_SENDER = 'noreply@sso.sparcs.org'


# issue reset pw token to user
def token_issue_reset_pw(user):
    ResetPWToken.objects.filter(user=user).delete()
    while True:
        tokenid = token_hex(24)
        if not ResetPWToken.objects.filter(tokenid=tokenid).count():
            break

    tomorrow = timezone.now() + datetime.timedelta(days=1)
    ResetPWToken.objects.filter(user=user).delete()

    ResetPWToken(tokenid=tokenid, expire_time=tomorrow, user=user).save()