import email
import getpass, imaplib
import os
import sys
import datetime
import json
import zipfile
from subprocess import check_output

data_dir = '..\data'
config_dir = '..\config'
fme_cmd = "call_fme.cmd"

now = datetime.datetime.now()
s_now = now.strftime("%Y-%m-%d %H:%M")
print s_now, "starting"

if 'data' not in os.listdir(".."):
    os.mkdir(data_dir)

#laden van de configuratie parameters
fp = open(config_dir + '\config.json', 'r')
js = fp.read()
fp.close()
config = json.loads(js)

print "Try to connect to " , config['mailserver']
imapSession = imaplib.IMAP4_SSL(config['mailserver'])
print "try to login"
typ, accountDetails = imapSession.login(config['userName'], config['passwd'])
if typ != 'OK':
    print 'Not able to sign in!'
    quit()

print "Login completed"

imapSession.select() #selecteerd default de INBOX
typ, data = imapSession.search(None, 'ALL')
#het lijkt er op dat de INBOX automatisch op volgorde van binnenkomst doorlopen wordt, en dit is precies wat we willen
  
print "Inbox selected"

# Iterating over all emails
for msgId in data[0].split():
    typ, messageParts = imapSession.fetch(msgId, '(RFC822)')
    if typ != 'OK':
        print 'Error fetching mail.'
        continue

    print "Marking mesg ", msgId, "For deletion"
    imapSession.store(msgId, '+FLAGS', '\\Deleted')

    emailBody = messageParts[0][1]
    mail = email.message_from_string(emailBody)
    #print('from = %s' % (mail['From']))
    #de not in operator is case sensitive
    #misschien later nog een betere controle
    if config['mailfrom'] not in mail['From']:
        print("wrong from address %s" % (mail['From']))
        continue
       
    for part in mail.walk():
        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()
        fileExtention = fileName[-4:]
        if fileExtention.upper() != ".ZIP":
            print fileName, " is not a zip file"
            continue

        print "cleaning up directory ", data_dir
        for root, dirs, files in os.walk(data_dir, topdown=False):
            for name in files:
                fileName2 = os.path.join(root, name)
                os.remove(fileName2)       
                #print "filename2 = ", fileName2

        if bool(fileName):
            filePath = os.path.join(data_dir, fileName)
            print "Unzipping ", fileName
            fp = open(filePath, 'wb')
            fp.write(part.get_payload(decode=True))
            fp.close()
            zf = zipfile.ZipFile(filePath, "r")
            zf.extractall(data_dir)
            zf.close()
            os.remove(filePath)
            print "fme aanroep = ", fme_cmd
            check_output(fme_cmd)
            print "fme aanroep is klaar"

print "Deleting marked messages"
imapSession.expunge()
imapSession.close()
imapSession.logout()

now = datetime.datetime.now()
s_now = now.strftime("%Y-%m-%d %H:%M")
print s_now, "done"