import smtplib
from email.message import EmailMessage
import flask
import datetime

from webapp import config, context

cached_connection = None

def test_connection_open(conn):
    try:
        status = conn.noop()[0]
    except:
        status = -1
    return True if status == 250 else False

def create_connection():
  conn = smtplib.SMTP_SSL(config.smtp_server)
  conn.login(config.smtp_user, config.smtp_password)
  return conn

def get_connection():
  global cached_connection
  if test_connection_open(cached_connection):
    return cached_connection

  cached_connection = create_connection()
  return cached_connection

def send_email(conn, subject, body, recipient_emails):
  msg = EmailMessage()
  msg.set_content(body)
  msg['Subject'] = subject

  sender_email = config.smtp_format.format(config.smtp_user)
  msg['From'] = f'LDAPWeb <{sender_email}>'
  msg['To'] = recipient_emails

  conn.send_message(msg)

def send_papertrail(title, description):
  username = flask.session.get('username')
  current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")

  subject = f'[LDAPWeb] {title}'
  body = f"Changed by {username} at {current_time}:\n\n{description or title}"
  recipients = config.papertrail_recipients

  conn = get_connection()
  send_email(conn, subject, body, recipients)
