#ht: 账户相关工具函数模块，处理验证码发送和验证
import typing
from datetime import timedelta

from django.core.cache import cache
from django.utils.translation import gettext
from django.utils.translation import gettext_lazy as _

from djangoblog.utils import send_email

#ht: 验证码有效时间为5分钟
_code_ttl = timedelta(minutes=5)


def send_verify_email(to_mail: str, code: str, subject: str = _("Verify Email")):
    """ht: 发送验证邮件
    Args:
        to_mail: 接收邮箱地址
        code: 验证码
        subject: 邮件主题，默认为"验证邮箱"
    """
    html_content = _(
        "You are resetting the password, the verification code is：%(code)s, valid within 5 minutes, please keep it "
        "properly") % {'code': code}
    send_email([to_mail], subject, html_content)


def verify(email: str, code: str) -> typing.Optional[str]:
    """ht: 验证邮箱和验证码是否匹配
    Args:
        email: 邮箱地址
        code: 验证码
    Returns:
        验证成功返回None，失败返回错误信息字符串
    """
    cache_code = get_code(email)
    if cache_code != code:
        return gettext("Verification code error")
    #ht: 验证成功后清除验证码，防止重复使用
    cache.delete(email)
    return None


def set_code(email: str, code: str):
    """ht: 将验证码存入缓存"""
    cache.set(email, code, _code_ttl.seconds)


def get_code(email: str) -> typing.Optional[str]:
    """ht: 从缓存获取验证码"""
    return cache.get(email)