#!/usr/bin/python

import smtplib
import urllib
import urllib2
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
from PyPDF2 import PdfFileWriter, PdfFileReader
import StringIO
import json
import pdb
import time

#defined variable
g_url ="http://localhost/smartlab_demo/su/emailresult/get"
g_url_config ="http://localhost/smartlab_demo/su/emailresult/config"
g_url_update ="http://localhost/smartlab_demo/su/emailresult/update"

#email client 
ge_url="http://localhost/smartlab_demo/su/emailclient/get"
ge_url_config="http://localhost/smartlab_demo/su/emailclient/config"
ge_url_update="http://localhost/smartlab_demo/su/emailclient/update"

subject = "SmartLab Laboratory Result"

def sendEmailClient(rec,subject,i_msg,i_att,support):
        server = ge_server
        r_addrs = [rec]
	a_support = support.split(",")
	to_addrs = r_addrs + a_support

        xfrom = ge_from
	msg = MIMEMultipart()
	msg['From'] = g_from
	msg['To'] = rec
	msg['Cc'] = support
	msg['Subject'] = "Smartlab L-Series Client Email" 
	msg.attach(MIMEText(i_msg))
	a_att=i_att.split(",")
	for att	in a_att :
		pdb.set_trace()
		if (att != "" ) :
			try :
				part = MIMEBase('application', "octet-stream")
				fn = att.encode('ascii')
        			part.set_payload( open(fn,"rb").read() )
        			Encoders.encode_base64(part)
        			part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(fn))
        			msg.attach(part)
			except:
				noop
	
	rst = True
        try :
		s = smtplib.SMTP(server,587)
        	s.set_debuglevel(7)
        	s.starttls()
        	s.login(ge_login,ge_password)
        	s.sendmail(xfrom, to_addrs, msg.as_string())
        	s.close()
	except:
		rst =False
	return rst

		

def sendEmail(rec,subject,i_msg,url,fname, pdf_pwd):
        server = g_server
        to_addrs = [rec]
        xfrom = g_from
	msg = MIMEMultipart()
	msg['From'] = g_from
	msg['To'] = rec
	msg['Subject'] = "Smartlab L-Series Result Report" 
	msg.attach(MIMEText(i_msg))
	u = urllib2.urlopen(url)
	
	inStr = StringIO.StringIO(u.read())
	outstr = StringIO.StringIO()
	inp_pdf = PdfFileReader(inStr)
	output = PdfFileWriter()
	for i in range(0,inp_pdf.getNumPages()) :
		output.addPage(inp_pdf.getPage(i))
	output.encrypt(pdf_pwd)
	output.write(outstr)
	buff = outstr.getvalue()
	inStr.close()
	outstr.close()

	part = MIMEBase('application', 'pdf')
   	part.set_payload(buff)
   	Encoders.encode_base64(part)
   	part.add_header('Content-Disposition',
           'attachment; filename="%s"' % fname )
   	msg.attach(part)

	rst = True
        try :
		s = smtplib.SMTP(server,587)
        	#s.set_debuglevel(7)
        	s.starttls()
        	s.login(g_login,g_password)
        	s.sendmail(xfrom, to_addrs, msg.as_string())
        	s.close()
	except:
		rst =False
	return rst


def get_config():
	u = urllib2.urlopen(g_url_config)
	rst = json.load(u)
	return rst
	
def get_ec_config():
	u = urllib2.urlopen(ge_url_config)
	rst = json.load(u)
	return rst

def update_status(xid,status,log) :
	data={'Mi_ResultEmailID':xid,'Mi_ResultEmailSendStatus' : status , 'Mi_ResultEmailLog' : log}
	data = urllib.urlencode(data)
	u = urllib2.urlopen(g_url_update,data)

def update_ge_status(xid,status,log) :
	data={'M_EmailClientID':xid,'M_EmailClientStatus' : status, 'M_EmailClientLog' : log}
	data = urllib.urlencode(data)
	u = urllib2.urlopen(g_url_update,data)


while True :
	conf = get_config()
	g_server = conf["M_EmailConfigServer"]
	g_from = conf["M_EmailConfigSender"]
	g_login = conf["M_EmailConfigUsername"]
	g_password = conf["M_EmailConfigPassword"]
	g_msg_format = conf["M_EmailConfigMessageFormat"]

	#email client
	ge_conf = get_ec_config()
	ge_server = conf["M_EmailConfigServer"]
	ge_from = conf["M_EmailConfigSender"]
	ge_login = conf["M_EmailConfigUsername"]
	ge_password = conf["M_EmailConfigPassword"]
	ge_msg_format = conf["M_EmailConfigMessageFormat"]
	
	
	u_email= urllib2.urlopen(g_url)
	dt = json.load(u_email)


	if dt :
		for d in  dt :
			url = d["url_report"]
			url_report="http://localhost" + url
			xid = d["Mi_ResultEmailID"]
			name = d["M_TitleName"] + ' ' + d["M_PatientName"]
			email = d["Mi_ResultEmailEmail"]
			nomorlab = d["T_OrderHeaderLabNumber"]
			tgl = d["T_OrderHeaderDate"]
			passwd = d["Mi_ResultEmailPassword"].encode('ascii','ignore')
			message = g_msg_format
	
			message= message.replace("{NAME}",name)
			message= message.replace("{NOLAB}",nomorlab)
			message= message.replace("{DATE}",tgl)
			fname = nomorlab + ".pdf"
			if sendEmail(email,subject,message,url_report,fname,passwd) :
				update_status(xid,'Y','Send Email : OK')
			else :
				update_status(xid,'C','Send Email : Error')


	#email client
	u_email =urllib2.urlopen(ge_url)
	dt = json.load(u_email)
	pdb.set_trace()
	if dt :
		for d in dt :
			xid = d['M_EmailClientID']
			att = d['attachment']
			email= d['S_SystemsEmailRND']
			tgl = d['M_EmailClientLastUpdate']
			message = "Title\t: %s\r\nMenu\t: %s\r\nCategory\t: %s\r\n\r\n%s" % (d['M_EmailClientTitle'],d['M_EmailClientMenu'],d['M_EmailClientCategory'],
d['M_EmailClientMessage']) 	
			subject = "[smartlab LSeries] " + d['M_EmailClientTitle']
			support = d['S_SystemsEmailSupport']
			if sendEmailClient(email,subject,message,att,support) :
				update_ge_status(xid,'Y')
			else :
				update_ge_status(xid,'C')
			
	time.sleep(20)

