from flask import flash

def flash_errors(form):
	#import pdb; pdb.set_trace()
	#import inspect
	#print(inspect.getmembers(form, lambda a:not(inspect.isroutine(a))))
	for field, errors in form.errors.items():
		if type(errors) ==list:
			for error in errors:
				flash(u"%s: %s" % (
					getattr(form, field).label.text,
					error
				), 'error')
		else:
			for key, value in errors.items():
				for error in value:
					flash(u"%s: %s" % (
						getattr(form.mobile_phone, key).label.text,
						error
					), 'error')


from urllib.parse import urlparse, urljoin
from flask import request, url_for

def is_safe_url(target):
	ref_url = urlparse(request.host_url)
	test_url = urlparse(urljoin(request.host_url, target))
	return test_url.scheme in ('http', 'https') and \
		   ref_url.netloc == test_url.netloc            

def get_redirect_target():
	for target in request.values.get('next'), request.referrer:
		if not target:
			continue
		if is_safe_url(target):
			return target           

from uuid import uuid4

def get_file_name():
	unique = str(uuid4())
	return unique      

from config import EMAIL_HOST, EMAIL_PORT, EMAIL_LOGIN, EMAIL_PASSWORD, DEBUG

def send_email(email_from, email_to, msg):
	if isinstance(email_to, str):
		email_to = [email_to]

	#if DEBUG:
	#    email_to = ['dedeco@gmail.com'] #DEBUG
		
	try:
		import smtplib
		import string # for tls add this line
		
		try:
			from email.utils import formatdate
		except ImportError:
			formatdate = datetime.datetime.today()

		if EMAIL_HOST and EMAIL_PORT:
			s = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT)
		else:
			s = smtplib.SMTP()            
					   
		if EMAIL_LOGIN and EMAIL_PASSWORD:
			s.ehlo() # for tls add this line
			s.starttls() # for tls add this line
			s.ehlo() # for tls add this line
			s.login(EMAIL_LOGIN, EMAIL_PASSWORD)
		try:
			s.sendmail(email_from, email_to, msg)
		finally:
			s.quit()                        
	except smtplib.SMTPException as  e:
		return False
	
	return True        