# vim: expandtab

# Copyright 2002 Raphaël Hertzog
# This file is distributed under the terms of the General Public License
# version 2 or (at your option) any later version.

import os, os.path, re, rfc822, email.Utils

def save_msg_in_dir(msg, dir, nb=20):
    """Add the message in the directory.
    Keep only the nb last messages."""
    if not os.path.isdir(dir):
        os.makedirs(dir)
    if os.path.isfile("%s/%d.txt" % (dir, nb)):
        os.unlink("%s/%d.txt" % (dir, nb))
    for i in range(nb - 1, 0, -1):
        if os.path.isfile("%s/%d.txt" % (dir, i)):
            os.rename("%s/%d.txt" % (dir, i), "%s/%d.txt" % (dir, i+1))
    f = open("%s/1.txt" % dir, "w")
    f.write(msg.as_string())
    f.close()
    os.chmod("%s/1.txt" % dir, 0664)

def generate_html_msg(src, dst, nb=20):
    """Convert all message in src directory 
    in HTML messages in dst directory"""
    # Clean old attachments first
    os.system("find %s -maxdepth 1 -type f -not -name '*.html' | xargs -r rm -f" % dst)
    # Regenerate HTML messages
    for i in range(nb):
        if os.path.isfile("%s/%d.txt" % (src, i + 1)):
            os.system("cd %s; /usr/bin/mhonarc -single %s/%d.txt > %d.html; chmod 0664 %d.html" % (dst, src, i+1, i+1, i+1))
    
def extract_info(msg):
    """Extract pseudo-header informations in a dictionnary"""
    info = {}
    if msg.is_multipart():
        for part in msg.walk():
            if part.get_type("text/plain") == "text/plain":
                body = part.get_payload(None, 1)
                break
    else:
        body = msg.get_payload(None, 1)
    lines = body.split("\n", 3)
    for i in range(3):
        res = re.match(r"^(\w+): (\S+)(.*)", lines[i])
        if res:
            field = res.group(1).lower()
            info[field] = res.group(2)
            if field == "subject":
                info[field] = info[field] + res.group(3)
        else:
            break
    if not info.has_key("subject"):
        info["subject"] = email.Utils.decode(msg.get("subject"))
    if msg.has_key("X-PTS-Url"):
        info["url"] = msg.get("X-PTS-Url")
    if msg.has_key("X-PTS-Package"):
        info["package"] = msg.get("X-PTS-Package")
    if msg.has_key("date"):
        t = rfc822.parsedate(msg["date"])
        if t:
            info["date"] = "%04d-%02d-%02d" % (t[0:3])
    return info

