import imapclient
from datetime import date

from config import Config
f=file('config.cfg')
cfg=Config(f)
try:
    server = imapclient.IMAPClient(cfg.host, use_uid=True, ssl=True)
    server.login(cfg.user, cfg.password)
    server.select_folder('INBOX')
except Error:
    print "error initializing server"
    server=None

def fetch_mail(myid):
    if server is None:
        raise ValueError("Server is None")
    m=server.fetch([myid],['ENVELOPE','RFC822'])
    m=m[myid]
    m["id"]=myid
    return m

def fetch_thread(tp): 
    return tp

def fetch_threads():
    if server is None:
        raise ValueError("Server is None")
    src=server.thread(criteria=[b'SUBJECT', b'service', b'SINCE', date(2017,02,01)])
    #, b'BEFORE', date(2017,08,01)
    return src


def flatten_threads(thrds, array=[], level=0):
    if level > 0:
        for t in thrds:
            if type(t) is tuple:
                array = array + (flatten_threads(t,[],1))
            else:
                array.append(t)
    else:
        for t in thrds: 
            array.append(flatten_threads(t,[],1))
    return array

def store_threads(thrds):
    for t in thrds:
        if type(t[0]) is int:
            th=db_session.query(MailThread).filter(MailThread.firstmail==t[0]).first()
            # Wenn nicht gefunden neuen anlegen
            if th == None:
                th=MailThread()
                th.firstmail=t[0]
                th.body=yaml.dump(t) # body zb (27422,27506), (27450,)
                th.islabeled=False
                th.opened=True
                th.istrained=False
            elif not th.body == yaml.dump(t): # Ansonsten body vergleichen
                th.body=yaml.dump(t) # body zb (27422,27506), (27450,)
                th.islabeled=False
                th.opened=True
                th.istrained=False
#            else:
#                th.body=yaml.dump(t)
            db_session.add(th)
            db_session.commit()
        

