#!/usr/bin/env python3
import smtplib
from email.message import EmailMessage
from .models import *
from django.conf import settings

def send_email(to, subject, body):
    msg = EmailMessage()
    msg.set_content(body)
    msg['Subject'] = subject
    msg['From'] = settings.EMAIL_HOST_USER
    msg['To'] = to

    s = smtplib.SMTP_SSL(settings.EMAIL_HOST, settings.EMAIL_PORT)
    s.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD)
    s.send_message(msg)
    s.quit()

def send_admin_email(admin, subject, body):
    if admin.user.email:
        send_email(admin.user.email, subject, body)

def send_user_message(whom, subject, content):
    um = UserMessage(
            sender='system',
            subject=subject,
            content=content
            )
    admin = None
    if isinstance(whom, AdminInfo):
        admin = whom
        um.admin = whom
    elif isinstance(whom, Tenant):
        um.tenant = whom
    else:
        raise Exception("Must specify either admin or tenant name")
    um.save()
    if admin:
        send_admin_email(admin, subject, content)

def admin_broadcast(subject, content):
    for admin in AdminInfo.objects.all():
        send_user_message(admin, subject, content)
