import imaplib
imaplib._MAXLINE = 400000
import email
import email.header
import datetime
from datetime import date, timedelta
import re
import os

"""
v005 - tjb - 13apr18 - added Spam count
v006 - tjb - 13apr18 - fixed problematic passwords.
v007 - tjb - 13apr18 - tidied up output formats
v008 - tjb - 13apr18 - improved screen prints
v009 - tjb - 15may18 - added customer service mailbox
v012 - tjb - 15jun18 - realised older v10 and v11 existed so get the number right and added teachingLaw@
v001 - tjb - 26jun18 - build code to capture email addresses to send to comms for removing from mail list.
v002 - tjb - 02aug18 - added pathTemp to account for new version of python having different base folder.
v003 - tjb - 14feb19 - changed password for ICT mailbox
v004 - tjb - 15feb19 - changed csv file to only have email address no From text
v005 - tjb - 18feb19 - checked to eliminate any duplicates
v006 - tjb - 09aug19 - changed the program to extract predictor emails
v007 - tjb - 10aug19 - extracted raw predictions from email body need to decide how to handle these
v008 - tjb - 10aug19 - remove testFile writes in the loop for mail boxes (root)
v009 - tjb - 10aug19 - remove work done on HEADER as it is not used for predictor application
v010 - tjb - 17aug19 - code to catch "0 - 3" type of google mail entry ie spaces between -
"""

#get name of path to the script file for opening files.
pathTemp = os.path.dirname(__file__)


testFile = open(pathTemp + "/predictorEmails.csv", "w")
testFile.write("Predictions\n")


listMailboxes =[
['your_email@gmail.com', 'your_gmail_app_password'],

]


longest = 42

def parse_mailbox(data):
    flags, b, c = data.partition(' ')
    separator, b, name = c.partition(' ')
    return (flags, separator.replace('"', ''), name.replace('"', ''))

def getNumberTotalEmail(folderName):
    # get number of entries in folder, this counts the emails and uses HEADER to find the 
    # people who sent the emails
    folder = folderName
    totalMsgs = 0
    mailCollection = []
     
    resp, data = obj.list('"{0}"'.format(folder), '*')
    if resp == 'OK':
        for mbox in data:
            flags, separator, name = parse_mailbox(bytes.decode(mbox))
            # Select the mailbox (in read-only mode)
            obj.select('"{0}"'.format(name), True)
            # Get ALL message numbers
            resp, msgnums = obj.search(None, 'ALL')
            mycount = len(msgnums[0].split())
            totalMsgs = totalMsgs + mycount
            #print(mycount)
            #print('{:<30} : {: d}\n'.format(name, mycount))
            for num in msgnums[0].split():
                #print(num)
                #data = obj.fetch(num, '(BODY.PEEK[HEADER])')
                #data = obj.fetch(num, '(RFC822)')
                #data = obj.fetch(num, 'ISO-8859-1')
                #msg = obj.message_from_string(data[0][1].decode('ISO-8859-1'))
                #msg = data[0][1].decode('ISO-8859-1')
                # msg is the email content
                msg = obj.fetch(num, '(RFC822)')
                msgString = str(msg)
                fromPoint = msgString.find("Email address")
                
                endPoint  = msgString.find("Rgds ")
                msgString = msgString[fromPoint:endPoint]
                msgString = msgString.replace("\\t"," ")
                if " - " in msgString:
                    msgString = msgString.replace(" - "," ")
                if "-" in msgString:
                    msgString = msgString.replace("-"," ")
                pieces = msgString.split("    ")
                name = pieces[0]
                pieces.pop(0)
                pieces.pop()
                
                while len(pieces) > 10:
                    pieces.pop()
                    
                print("PIECES")
                print(pieces)
                print("END OF PIECES")
                
                pathTemp = os.path.dirname(__file__)
                testFile = open(pathTemp + "/predictorEmails.csv", "a")
                
                print(" ")
                print(name)
                testFile.write("\n" + name + "\n")
                for parts in pieces:
                    #print(parts)
                    
                    partsAway = parts[-1]
                    partsHome = parts[-3]
                    partsHome = partsHome[0]
                    parts = parts.lstrip()
                    parts = parts[:-5]
                    parts = parts.replace(","," ")
                    

                    
                    testFile.write(parts + "," + partsHome + "," + partsAway + "\n")
                    print(parts + " " + partsHome + " " + partsAway)
                    #print("Home ", partsHome)
                    #print("Away ", partsAway)
                print(" ")               

            
            
            return totalMsgs

for inboxPair in listMailboxes:
       
    try:
        obj = imaplib.IMAP4_SSL("imap.gmail.com", 993)
        inbox = inboxPair[0]
        password = inboxPair[1]
        length = len(inbox)
        
        obj.login(str(inbox), str(password)) 
        obj.select('Inbox') 
        obj.search(None,'ALL') 
        
        # Count the INBOX unread emails
        status, response = obj.status('INBOX', "(UNSEEN)")
        unreadcount = str(response[0].split()[2])
        unreadcount = unreadcount.strip('\'b)')
        
        count = getNumberTotalEmail('predictor/thisWeek')
        
        #obj.select('badEmailAddress')
        #sent = len(list_mailbox_content(obj, filter))

        #obj.select('badEmailAddress')
        #sentcount, mailCollection = mailbox_counts(obj, 'badEmailAddress')
        
        print(inbox + (longest -length) *" " + " OK")
        print("Number of emails is " + str(count))
        #print(collection)
        #print("badEmailAddress sent  is " + str(sent))
        #print("badEmailAddress count is " + str(counts))
        
        
        #testFile.write(inbox + "," + str(count) + "\n") 
         
         
    except imaplib.IMAP4.error: 
        print("\n" + inbox + " Log in failed.\n")

    
    
    
      
            
testFile.close()   