from flask import url_for, render_template
from flask_mail import Message
from app import app, mail
from itsdangerous import URLSafeTimedSerializer
from config import V5Config

def send_mail(dest, subject, html="", body=""):
    m = Message(recipients=[dest], subject=subject, html=html, body=body)
    mail.send(m)

def send_reset_password_mail(name, email):
    ts = URLSafeTimedSerializer(app.config["SECRET_KEY"])
    token = ts.dumps(email, salt='email-confirm-key')
    reset_url = f"https://{V5Config.DOMAIN}" \
        + url_for('reset_password', token=token)
    subject = "Réinitialisation du mot de passe"
    html = render_template('email/reset_password.html', reset_url=reset_url,
        name=name)
    body = render_template('email/reset_password.md', reset_url=reset_url,
        name=name)
    if V5Config.SEND_MAILS:
        send_mail(email, subject, html=html, body=body)
    else:
        print(f"Reset password url: {reset_url}")

def send_validation_mail(name, email):
    ts = URLSafeTimedSerializer(app.config["SECRET_KEY"])
    token = ts.dumps(email, salt='email-confirm-key')
    confirm_url = f"https://{V5Config.DOMAIN}" \
        + url_for('activate_account', token=token)
    subject = "Confirmez votre email pour compléter l'inscription"
    html = render_template('email/activate.html', confirm_url=confirm_url,
        name=name)
    body = render_template('email/activate.md', confirm_url=confirm_url,
        name=name)
    if V5Config.SEND_MAILS:
        send_mail(email, subject, html=html, body=body)
    else:
        print(f"Email confirmation url: {confirm_url}")
