# -*- coding: utf-8 -*-
# Tabellio -- software suite for deliberative assemblies
#          -- suite logicielle pour assemblées délibératives
#          -- http://www.tabellio.org/
# Copyright (C) 2006 Parlement de la Communauté française de Belgique

# This file is part of Tabellio.

# Tabellio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# Tabellio 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 General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import zipfile
import os

def unzipToDictionary(inputFilename):
    """
    Based on a inputFileName, this routine returns a dictionary of
    key = zi.fileName / value = tuple(zi, data)
    """
    inz = None
    dic = {}
    try:
        inz = zipfile.ZipFile(inputFilename)
        zilist = inz.infolist()
        for zi in zilist:
            data = inz.read(zi.filename)
            dic[zi.filename] = (zi, data)
    finally:
        if inz != None:
            inz.close()
    return dic

def _writeToFile(filename, data):
    f = None
    try:
        f = open(filename, "wb")
        f.write(data)
    finally:
        if f != None:
            f.close()

def unzipToDirectory(inputFilename, d, prefix=""):
    """
    Based on a inputFileNmae, this routine returns a dictionary of
    key = zi.fileName / value = tuple(zi, data)
    and save all entries in the directory 'd'
    """
    inz = None
    dic = {}
    try:
        inz = zipfile.ZipFile(inputFilename)
        zilist = inz.infolist()
        for zi in zilist:
            data = inz.read(zi.filename)
            dic[zi.filename] = (zi, data)
            _writeToFile(os.path.join(d, prefix+zi.filename), data)
    finally:
        if inz != None:
            inz.close()
    return dic
