from setup import app, CONFIG
from flask_mail import Message
from flask import render_template
from typing import List

class Email:
    def __init__(self, mail_manager):
        with app.app_context():
            app.config["TESTING"] = CONFIG['email']['testing']
            app.config["MAIL_SERVER"] = CONFIG['email']['mail_server']
            app.config["MAIL_PORT"] = CONFIG['email']['mail_port']
            app.config["MAIL_USE_TLS"] = CONFIG['email']['mail_use_tls']
            app.config["MAIL_USE_SSL"] = CONFIG['email']['mail_use_ssl']
            app.config["MAIL_USERNAME"] = CONFIG['email']['mail_username']
            app.config["MAIL_PASSWORD"] = CONFIG['email']['mail_password']

            self.mail_manager = mail_manager.init_app(app)

    def _send_email(self, recipients: List[str], subject_str: str, body_text: str, body_html: str = None):

        sender = CONFIG['email']['default_mail_sender']
        message = Message(subject_str, sender=sender, recipients=recipients, body=body_text)

        if body_html is not None:
            message.html = body_html
        
        self.mail_manager.send(message)

    def send_email(self, to_email_address: str, subject_str: str, body_text: str, body_html: str):
        recipients = [to_email_address]
        self._send_email(recipients, subject_str, body_text, body_html)

    def send_templated_email(self, to_email_address: str, subject_str: str, template_name_stem: str, email_model):
        txt_template_name = f"email/{template_name_stem}.txt"
        html_template_name = f"email/{template_name_stem}.html"
        body_text = render_template(txt_template_name, model=email_model)
        body_html = render_template(html_template_name, model=email_model)

        self.send_email(to_email_address, subject_str, body_text, body_html)
