import string
import poplib

pophost = 'pop'


class Headers:

    def __init__(self):
        self.hdrs = {}

    def append(self, header):
        if not header:
            return
        parts = string.split(header, ': ', 1)
        name = string.capitalize(parts[0])
        if len(parts) > 1:
            value = parts[1]
        else:
            value = ''
        curr = self.hdrs.get(name)
        if not curr:
            self.hdrs[name] = value
            return
        if type(curr) is type(''):
            curr = self.hdrs[name] = [curr]
        curr.append(value)

    def __getitem__(self, name):
        return self.hdrs.get(string.capitalize(name), '')


class Msg:

    def __init__(self, mbox, msgnum):
        self.mbox = mbox
        self.msgnum = msgnum
        self.read_headers()

    def read_headers(self):
        res = self.mbox.top(self.msgnum, 0)
        hdrs = Headers()
        hdr = None
        for line in res[1]:
            if line and line[0] in string.whitespace:
                hdr = hdr + '\n' + line
            else:
                hdrs.append(hdr)
                hdr = line
        hdrs.append(hdr)
        self.hdrs = hdrs
        return hdrs

    def read_body(self):
        res = self.mbox.retr(self.msgnum)
        lines = res[1]
        for i in range(len(lines)):
            if not lines[i]:
                break
        self.body = string.join(lines[i:], '\n')
        return self.body


class Mbox:

    def __init__(self, name, passwd):
        self.mbox = poplib.POP3(pophost)
        self.mbox.user(name)
        self.mbox.pass_(passwd)

    def __getitem__(self, i):
        try:
            return Msg(self.mbox, i + 1)
        except poplib.error_proto:
            raise IndexError

    def __len__(self):
        len, size = self.mbox.stat()
        return len
