﻿import base64
import requests
import json
import os
from os import path
import shutil
import glob
import pymysql.cursors
import pymysql
import uuid



# Something in lines of http://stackoverflow.com/questions/348630/how-can-i-download-all-emails-with-attachments-from-gmail
# Make sure you have IMAP enabled in your gmail settings.
# Right now it won't download same file name twice even if their contents are different.
# Gmail as of now returns in bytes but just in case they go back to string this line is left here.

import email
import getpass, imaplib
import os
import sys
import time


#
# Connect to Gmail and Download Resumes 
#
detach_dir = 'storage/app/resumes'
#if 'attachments' not in os.listdir(detach_dir):
#    os.mkdir('attachments')

userkey = '3SYCRFQHOOT'
subuserid = 'Cloudely, Inc'
version = '8.0.0'

# service url- provided by RChilli
url="http://rest.rchilli.com/RChilliParser/Rchilli/parseResumeBinary"

db = pymysql.connect (host="cldy-hub-db-prod-do-user-1524670-0.a.db.ondigitalocean.com",
                     user="doadmin",
                     passwd="jmbly6e4obtma5z0",
                     db="defaultdb",
                     port=25060,
                     charset='utf8mb4',
                     cursorclass=pymysql.cursors.DictCursor)

userName = 'resume@cloudely.com'
passwd = 'welcome2cloudely'

print ("Starting to Process Resume Inbox")

imapSession = imaplib.IMAP4_SSL('imap.gmail.com',993)
typ, accountDetails = imapSession.login(userName, passwd)
if typ != 'OK':
    print ('Not able to sign in!')
    raise

imapSession.select('Inbox')
# typ, data = imapSession.search(None, 'ALL')
typ, data = imapSession.search(None, '(UNSEEN)')
if typ != 'OK':
    print ('Error searching Inbox.')
    raise

# Iterating over all emails
for msgId in data[0].split():
    typ, messageParts = imapSession.fetch(msgId, '(RFC822)')

    if typ != 'OK':
        print ('Error fetching mail.')
        raise 

    #print(type(emailBody))
    emailBody = messageParts[0][1]
    #mail = email.message_from_string(emailBody)
    mail = email.message_from_bytes(emailBody)

    for part in mail.walk():
        #print (part)
        if part.get_content_maintype() == 'multipart':
            # print part.as_string()
            continue
        if part.get('Content-Disposition') is None:
            # print part.as_string()
            continue

        fileName = part.get_filename()

        if bool(fileName):
            filePath = os.path.join(detach_dir, 'new', fileName)
            if not os.path.isfile(filePath) :
                print (fileName)
                fp = open(filePath, 'wb')
                fp.write(part.get_payload(decode=True))
                fp.close()

                with open(filePath, "rb") as fp:
                    encoded_string = base64.b64encode(fp.read())

                with open(filePath, "rb") as fp:
                    file_content = fp.read()

                data64 = encoded_string.decode('UTF-8')
                headers = {'content-type': 'application/json'}
                body =  """{"filedata":\""""+data64+"""\","filename":\""""+ fileName+"""\","userkey":\""""+ userkey+"""\",\"version\":\""""+version+"""\",\"subuserid\":\""""+subuserid+"""\"}"""

                response = requests.post(url,data=body,headers=headers)
                resp =json.loads(response.text)

                #read values from response
                if resp.get('ResumeParserData'):
                    Resume =resp["ResumeParserData"]

                    with db.cursor() as cursor:
                        #sql = "INSERT INTO `resumes` (`id`, `first_name`, `last_name`, `email`, `resume_filename`, `source`, `resume_json`, `resume_binary_file`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE resume_json = %s"
                        #cursor.execute(sql, (str(uuid.uuid1()), str(Resume["FirstName"]).capitalize(), str(Resume["LastName"]).capitalize(), str(Resume["Email"]).lower(), fileName, "Email Inbox", response.text, file_content, response.text))
                        sql = "INSERT INTO `resumes` (`uuid`, `status`, `email`, `resume_filename`, `source`, `resume_json`, `resume_binary_file`) VALUES (%s, %s, %s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE resume_json = %s"
                        cursor.execute(sql, (str(uuid.uuid1()), 'New', 'mmellon', fileName, "Email Inbox", response.text, file_content, response.text))                        
                        db.commit()

                    #shutil.move(path.join(srcDirectory, filename), destDirectory) 
                    os.remove(path.join(filePath))

                else:
                #error
                    error =resp["error"]
                    print(error)
                                




imapSession.close()
imapSession.logout()