from app import mail
from flask import current_app, Flask, render_template
from flask_mail import Message
from threading import Thread
from typing import Any


def create_message(recipient: str, subject: str, template: str, **kwargs: Any) -> Message:
    subject_prefix: str = current_app.config['NOPAQUE_MAIL_SUBJECT_PREFIX']
    msg: Message = Message(
        body=render_template(f'{template}.txt.j2', **kwargs),
        html=render_template(f'{template}.html.j2', **kwargs),
        recipients=[recipient],
        subject=f'{subject_prefix} {subject}'
    )
    return msg


def _send(app: Flask, msg):
    with app.app_context():
        mail.send(msg)


def send(msg: Message, *args, **kwargs):
    thread = Thread(target=_send, args=[current_app._get_current_object(), msg])
    thread.start()
    return thread