from server import *

from email.message import EmailMessage
import smtplib
import traceback

def send_message(msgtype, recipients, **kwargs):
	msg = EmailMessage()
	msg['From'] = config['MAIL_FROM']
	msg['To'] = ', '.join([r.replace(',', '') for r in recipients])
	cc = kwargs.pop('cc', [])
	if cc:
		msg['Cc'] = ', '.join([r.replace(',', '') for r in cc])
	try:
		msg['Subject'] = render_template('mails/'+msgtype+'.subject', **kwargs)
		msg.set_content(render_template('mails/'+msgtype+'.body', **kwargs))
		if not config.get('MAIL_SERVER'):
			return
		s = smtplib.SMTP(config['MAIL_SERVER'])
		if config.get('MAIL_ADDRESS_OVERWRITE'):
			s.send_message(msg, to_addrs=[config['MAIL_ADDRESS_OVERWRITE']])
		else:
			s.send_message(msg)
		s.quit()
	except:
		traceback.print_exc()

def notify_users(msgtype, uids, **kwargs):
	recipients = []
	exclude = kwargs.pop('exclude_uids', [])
	for uid in uids:
		user = query('SELECT * FROM users WHERE id = ?', uid)
		if not user or user[0]['id'] in exclude:
			continue
		if not user[0]['fsacc'] or not user[0]['mail_notifications']:
			continue
		if msgtype in user[0] and not user[0][msgtype]:
			continue
		if user[0]['realname']:
			recipients.append('%s <%s@%s>'%(user[0]['realname'], user[0]['fsacc'],
						config['MAIL_SUFFIX']))
		else:
			recipients.append('%s@%s'%(user[0]['fsacc'], config['MAIL_SUFFIX']))
	cc = kwargs.get('cc', [])
	if kwargs.pop('importend', False):
		cc.append(config['MAIL_DEFAULT'])
	if kwargs.pop('notify_admins', False):
		cc.append(config['MAIL_ADMINS'])
	if not recipients:
		recipients = cc
		cc = []
	if not recipients:
		return
	kwargs['cc'] = cc
	send_message(msgtype, recipients, **kwargs)

def notify_mods(msgtype, course_id, **kwargs):
	users = query('SELECT * FROM responsible WHERE course_id = ?', course_id)
	uids = []
	for user in users:
		if msgtype in user and not user[msgtype]:
			continue
		uids.append(user['user_id'])
	notify_users(msgtype, uids, **kwargs)

def notify_admins(msgtype, **kwargs):
	try:
		send_message(msgtype, [config['MAIL_ADMINS']], **kwargs)
	except:
		traceback.print_exc()