# -*- coding: utf-8 -*-

import codecs, os, time, cfg

def get_echoarea(name):
    try:
        return open('echo/%s' % name).read().splitlines()
    except:
        return ''

def dateg(d,f):
    return time.strftime(f, time.gmtime(int(d)))

def _parz(msg):
    pz = msg.splitlines()
    mo = dict()
    optz = pz[0].split('/')
    mo.update( dict(zip(optz[::2],optz[1::2])) )
    for i_,n in enumerate(('echoarea','date','msgfrom','addr','msgto','subj')):
        i = i_ + 1
        mo[n] = pz[i]
    mo['date'] = int(mo['date'])
    mo['msg'] = '\n'.join(pz[8:])
    return mo


for ea in cfg.r(cfg.allea):
    if not os.path.exists('../%s' % ea):
        os.makedirs('../%s' % ea)
    my = get_echoarea(ea) or []
    f = codecs.open('../%s.txt' % ea,'w','utf-8')
    for i_,m in enumerate(my):
        i = i_+1
        try:
            mo = _parz(codecs.open('msg/%s' % m,'r','utf-8').read())
        except:
            mo = dict(date=0,msgfrom='',addr='',msgto='',msg='',subj='')
        sdate = dateg(mo['date'],'%d/%m/%y %H:%M')
        buf = m + '\n' + mo['msgfrom'] + '\n(' + str(mo['addr']) + ') (' + sdate + ' GMT)\nmsgto: ' + mo['msgto'] + '\n' + mo['subj'] + '\n\n' + mo['msg']
        codecs.open('../%s/%s.txt' % (ea,str(i).zfill(4)),'w','utf-8').write(buf)
        f.write('== %s ========================= ' % i + buf + '\n\n\n')
    f.close()
