import smtplib
from email.message import EmailMessage
from flask import current_app, url_for


def _send_mail(to_email: str, subject: str, body: str):
    if not current_app.config['MAIL_ENABLED']:
        current_app.logger.info(f"MAIL DISABLED -> To: {to_email} | Subject: {subject}\n{body}")
        return

    msg = EmailMessage()
    msg['Subject'] = subject
    msg['From'] = current_app.config['MAIL_FROM']
    msg['To'] = to_email
    msg.set_content(body)

    with smtplib.SMTP(current_app.config['SMTP_HOST'], current_app.config['SMTP_PORT'], timeout=20) as smtp:
        smtp.starttls()
        smtp.login(current_app.config['SMTP_USERNAME'], current_app.config['SMTP_PASSWORD'])
        smtp.send_message(msg)


def send_welcome_email(user, temporary_password: str):
    login_url = url_for('main.login', _external=True)
    body = f"""Hej {user.display_name},

Din TuxiNet StreamHub-konto er blevet oprettet.

Brugernavn: {user.username}
Midlertidig kode: {temporary_password}
Login: {login_url}

Du skal ændre din kode ved første login.

Hilsen
TuxiNet StreamHub
"""
    _send_mail(user.email, 'Velkommen til TuxiNet StreamHub', body)


def send_reset_email(user, reset_url: str):
    body = f"""Hej {user.display_name},

Du har bedt om at nulstille din adgangskode.

Reset-link:
{reset_url}

Linket udløber automatisk.
Hvis du ikke har bedt om dette, kan du ignorere mailen.

Hilsen
TuxiNet StreamHub
"""
    _send_mail(user.email, 'Nulstil din adgangskode', body)
