import imapclient
from datetime import date

from config import Config
f=file('config.cfg')
cfg=Config(f)
server = imapclient.IMAPClient(cfg.host, use_uid=True, ssl=True)
server.login(cfg.user, cfg.password)
server.select_folder('INBOX')


def fetch_mail(myid):
    m=server.fetch([myid],['ENVELOPE','RFC822'])
    m=m[myid]
    m["id"]=myid
    return m

def fetch_thread(tp): 
    return tp

def fetch_threads():
    src=server.thread(criteria=[b'SUBJECT', b'service', b'SINCE', date(2017,05,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
