#!/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
import MySQLdb as mdb
import sys

#hardcoded email type
EMAIL_TYPE = 2
MAX_PER_JOB = 10

def mydb():
    try :
        server = 'localhost'
        user = 'hsgw'
        passwd = 'hsgw!102938'
        dbname = 'one_preorder_dev'
        return mdb.connect(server , user, passwd, dbname)
    except mdb.Error, e :
        print "Error %d: %s" % (e.args[0],e.args[1])
        sys.exit()


def sendEmailText(rec,subject,i_msg,cc):
        server = g_server
        to_addrs = [rec]
        xfrom = g_from
	msg = MIMEMultipart()
	msg['From'] = g_from
	msg['To'] = rec
        if cc != "" :
            msg['Cc'] = cc
            to_addrs = [rec,cc]
	msg['Subject'] = subject
	msg.attach(MIMEHtml(i_msg))
	
	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 getMailConfig(db) :
    try :
        cur = db.cursor(mdb.cursors.DictCursor)
        sql = '''
        select * from m_emailconfig where M_EmailConfigIsActive = 'Y' limit 0,1
        '''
        cur.execute(sql)
        rows = cur.fetchall()
        cur.close()
        if rows :
            return rows[0]
        return false
    except mdb.Error, e :
        print "Error %d: %s" % (e.args[0],e.args[1])
        sys.exit()

def getHomeService(db,retry) :
    try :
        cur = db.cursor(mdb.cursors.DictCursor)
        sql = '''
        select outboxID, outboxRecipient, outboxMessage
        from one_gateway.outbox
        join preorder_header on outboxRefID = PreOrder_HeaderID
        where outboxIsSent = 'N' and outboxTypeID = %s
        and outboxIsActive = 'Y' and outboxRetry < retry
        order by outboxID desc
        limit 0,%s
        '''
        inp = (EMAIL_TYPE,MAX_PER_JOB)
        cur.execute(sql,inp)
        rows = cur.fetchall()
        cur.close()
        return rows
    except mdb.Error, e :
        print "Error %d: %s" % (e.args[0],e.args[1])
        sys.exit()
def updateHomeService(db, id, success) :
    try :
        cur = db.cursor(mdb.cursors.DictCursor)
        if success :
            sql = '''
            update one_gateway.outbox set outboxIsSent = 'Y',
            outboxSentDate = now() where outboxID=%s
            '''
        else :
            sql = '''
            update one_gateway.outbox set outboxRetry = outboxRetry + 1
            where outboxID=%s
            '''
        inp = ( id )
        cur.execute(sql,inp)
        cur.close()
    except mdb.Error, e :
        print "Error %d: %s" % (e.args[0],e.args[1])
        sys.exit()

# get db
db = mydb()
config = getMailConfig(db)
g_server = config["M_EmailConfigServer"]
g_login = config["M_EmailConfigUsername"]
g_password = config["M_EmailConfigPassword"]
g_from = config["M_EmailConfigSender"]
g_max_retry= config["M_EmailConfigMaxRetry"]
g_cc = config["M_EmailConfigCc"]

rows_hs = getHomeService(db,g_max_retry)

for r in row_hs :
    id = r['outboxID']
    email = r['outboxRecipient']
    subject = r['Home Service Confirmation']
    message = r['outboxMessage']
    rst = sendEmailText(email,subject,message) 
    updateHomeService(db,id,rst)

