from email.message import EmailMessage
import smtplib
import traceback

from server import *

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', []) #pylint: disable=invalid-name
	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
		mailserver = smtplib.SMTP(config['MAIL_SERVER'])
		if config.get('MAIL_ADDRESS_OVERWRITE'):
			mailserver.send_message(msg, to_addrs=[config['MAIL_ADDRESS_OVERWRITE']])
		else:
			mailserver.send_message(msg)
		mailserver.quit()
	except: #pylint: disable=bare-except
		# we musst not raise an exception here, else we would send another mail, rinse and repeat
		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 'notify_'+msgtype in user[0] and not user[0]['notify_'+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', []) #pylint: disable=invalid-name
	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 = [] #pylint: disable=invalid-name
	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:
		uids.append(user['user_id'])
	notify_users(msgtype, uids, **kwargs)

def notify_admins(msgtype, **kwargs):
	try:
		send_message(msgtype, [config['MAIL_ADMINS']], **kwargs)
	except: #pylint: disable=bare-except
		# we musst not raise an exception here, else we would send another mail, rinse and repeat
		traceback.print_exc()

@app.route('/internal/user/<int:user>/notifications')
@register_navbar('Benachrichtigungen', icon='bell', userendpoint=True)
@mod_required
def user_notifications(user):
	return render_template('notifications.html', user=query('SELECT * FROM users WHERE id = ?', user)[0])