# coding: utf8
# Debian Contributors data mining utilities
#
# Copyright (C) 2013--2014  Enrico Zini <enrico@debian.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
import tempfile
import mailbox
import gzip
import shutil
import os.path
import logging

log = logging.getLogger(__name__)

class CompressedMbox(mailbox.mbox):
    """
    Read-only access of a compressed mbox using a temporary file for the
    uncompressed version
    """
    def __init__(self, pathname):
        self.tempfile = tempfile.NamedTemporaryFile()
        with gzip.open(pathname) as fd:
            shutil.copyfileobj(fd, self.tempfile)
            self.tempfile.flush()
        mailbox.mbox.__init__(self, self.tempfile.name)

    def close(self):
        # mailbox.mbox is not a new-style object :'(
        mailbox.mbox.close(self)
        self.tempfile.close()

def get_mailbox(pathname):
    """
    Create the right Mailbox object for a pathname
    """
    if os.path.isdir(pathname):
        return mailbox.Maildir(pathname)
    elif pathname.endswith(".gz"):
        return CompressedMbox(pathname)
    else:
        return mailbox.mbox(pathname)

