#!/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.MIMEImage import MIMEImage
from email import Encoders
from PyPDF2 import PdfFileWriter, PdfFileReader
import StringIO
import json
import pdb
import time
import datetime
import os 
import sys 

#defined variable
#testing 
g_url ="http://localhost/one-api/keu/email_on_hold_titipan/first_reminder"
status_url ="http://localhost/one-api/keu/email_on_hold_titipan/log"
second_url ="http://localhost/one-api/keu/email_on_hold_titipan/second_reminder"
tagihan_awal_url = "http://localhost/one-api/keu/email_on_hold_titipan/tagihan_awal"
status_awal_url ="http://localhost/one-api/keu/email_on_hold_titipan/log_awal"



subject = "Reminder"
email_error = ""

def sendEmail(rec,subject,i_msg, arr_url,fname,cc ):
    server = g_server
    a_rec = [ x.strip() for x in rec.split(",")]
    to_addrs = [cc] + a_rec
    #to_addrs = [rec]
    xfrom = g_from
    msg = MIMEMultipart()
    msg['From'] = g_from
    msg['To'] = rec
    msg['Cc'] = cc
    msg['Subject'] = subject
    email_error = ""
    try :
        msg.attach(MIMEText(i_msg,"html","utf-8"))
    except:
        print "Msg Unicode : " + i_msg
        email_error = "Message Unicode : " + i_msg
        return False
    #pdb.set_trace()
    print "Email : " + rec  
    print "Server : " + server
    print "Login : " + g_login
    idx = 1
    for url in arr_url:
        if url != "" :
            try:
                u = urllib2.urlopen(url)
                idx_fname = fname + str(idx) +  "-received.jpg"
                part = MIMEImage(u.read(),name= idx_fname)
                part.add_header("Content-ID","<image-received-att-" + str(idx) + "@pramita.co.id>")
                part.add_header('X-Attachment-Id', idx_fname)
                part.add_header('Content-Disposition', 'inline', filename=fname)
                msg.attach(part)
                idx = idx+1
            except :
                print "Read Attachment Error : "  + ":" + url
                email_error = "Read Attachment Error : " + url
                return False

    rst = True
    try :
        s = smtplib.SMTP(server,587)
        #s.set_debuglevel(5)
        s.starttls()
        s.login(g_login,g_password)
        s.sendmail(xfrom, to_addrs, msg.as_string())
        s.close()
    except smtplib.SMTPException as e:
        error_message = str(e)
        print "Error Smtp: " + error_message + "\n"
        rst = False
    except:
        rst =False
    return rst

def post_status(keuID,status):
    jdata = {"id" : keuID, "status" : status , "note": email_error }
    data = json.dumps(jdata).encode("utf8")
    req = urllib2.Request(status_url, data, {'Content-Type': 'application/json'})
    f = urllib2.urlopen(req)
    response = f.read()
    f.close()

def post_status_awal(issueID,status):
    jdata = {"id" : issueID, "status" : status , "note": email_error }
    data = json.dumps(jdata).encode("utf8")
    req = urllib2.Request(status_awal_url, data, {'Content-Type': 'application/json'})
    f = urllib2.urlopen(req)
    response = f.read()
    f.close()


#first reminder
email_on_hold = urllib2.urlopen(g_url)
dt = json.load(email_on_hold)
email_on_hold.close()

today = datetime.datetime.today()
if dt['status'] == "ERR" :
    print today.strftime("%Y-%m-%d %H:%M:%S : Sending Email") + " : " +  dt["message"]
    sys.exit()

config = dt['config']
data = dt['data']

print today.strftime("%Y-%m-%d %H:%M:%S : Start First Reminder Email") + " : " +  str(len(dt["data"]))
g_server = config['ConfOnHoldServer']
g_login = config['ConfOnHoldSenderEmail']
g_password = config['ConfOnHoldSenderPassword']
email_name = config['ConfOnHoldSenderName']
email_cc = config['ConfOnHoldCc']

email_cc = "padmanto@gmail.com"

g_from = email_name + "<" + g_login + ">"

for d in  data :
    email = d['email']
    xmessage = d['message']
    url = d['attachment']
    billNo = d["F_BillNo"]
    fname = billNo 
    company = d["M_CompanyName"]
    keuID = d["KeuReminderID"]
    if sendEmail(email,subject,xmessage,url,fname,email_cc): 
        today = datetime.datetime.today()
        print today.strftime("%Y-%m-%d %H:%M:%S : Sending Email") + " : " + 'Update Status OK : ' + billNo  + " "  + company + " to " + email
        post_status(keuID, "Y")
    else :
        today = datetime.datetime.today()
        print today.strftime("%Y-%m-%d %H:%M:%S : Sending Email") + " : " + 'Update Status ERR : ' + billNo + " " + company + " to " + email
        post_status(keuID,"E")
         
#second reminder 

subject = "Final Reminder"
second_email_on_hold = urllib2.urlopen(second_url)
dt = json.load(second_email_on_hold)
today = datetime.datetime.today()
if dt['status'] == "ERR" :
    print today.strftime("%Y-%m-%d %H:%M:%S : Sending Second Reminder Email") + " : " +  dt["message"]
    sys.exit()


config = dt['config']
data = dt['data']

second_email_on_hold.close()

g_server = config['ConfOnHoldServer']
g_login = config['ConfOnHoldSenderEmail']
g_password = config['ConfOnHoldSenderPassword']
email_name = config['ConfOnHoldSenderName']
email_cc = config['ConfOnHoldCc']
g_from = email_name + "<" + g_login + ">"

email_cc = "padmanto@gmail.com"

for d in  data :
    email = d['email']
    xmessage = d['message']
    url = d['attachment']
    billNo = d["F_BillNo"]
    fname = billNo + "-received.jpg"
    company = d["M_CompanyName"]
    keuID = d["KeuReminderID"]
    if sendEmail(email,subject,xmessage,url,fname,email_cc): 
        today = datetime.datetime.today()
        print today.strftime("%Y-%m-%d %H:%M:%S : Sending Second Reminder Email") + " : " + 'Update Status OK : ' + billNo  + " "  + company + " to " + email
        post_status(keuID, "Y")
    else :
        today = datetime.datetime.today()
        print today.strftime("%Y-%m-%d %H:%M:%S : Sending Second Reminder Email") + " : " + 'Update Status ERR : ' + billNo + " " + company + " to " + email
        post_status(keuID,"E")

#tagihan awal

subject = "Reminder"
tagihan_awal_email = urllib2.urlopen(tagihan_awal_url)
dt = json.load(tagihan_awal_email)
today = datetime.datetime.today()
if dt['status'] == "ERR":
    print today.strftime("%Y-%m-%d %H:%M:%S : Sending Tagihan Awal Email") + " : " +  dt["message"]
    sys.exit()

config = dt['config']
data = dt['data']
tagihan_awal_email.close()

g_server = config['ConfOnHoldServer']
g_login = config['ConfOnHoldSenderEmail']
g_password = config['ConfOnHoldSenderPassword']
email_name = config['ConfOnHoldSenderName']
email_cc = config['ConfOnHoldCc']
g_from = email_name + "<" + g_login + ">"

for d in  data :
    email = d['email']
    xmessage = d['message']
    url = d['attachment']
    billNo = d["F_BillNo"]
    company = d["M_CompanyName"]
    keuID = d["KeuReminderID"]
    issueID = d["F_BillIssueID"]
    fname = billNo
    if sendEmail(email, subject,xmessage,url,fname,email_cc):
        today = datetime.datetime.today()
        print today.strftime("%Y-%m-%d %H:%M:%S : Sending Sending Tagihan Awal Email") + " : " + 'Update Status OK : ' + billNo  + " "  + company + " to " + email
        post_status_awal(issueID, "S")
    else :
        today = datetime.datetime.today()
        print today.strftime("%Y-%m-%d %H:%M:%S : Sending Sending Tagihan Awal Email") + " : " + 'Update Status ERR : ' + billNo + " " + company + " to " + email
        post_status_awal(issueID,"E")
