# -*- coding: UTF-8 -*-


# Expression
# By: Frederic Peters <fpeters@entrouvert.com>
#     Emmanuel Raviart <eraviart@entrouvert.com>
#
# Copyright (C) 2004 Entr'ouvert, Frederic Peters & Emmanuel Raviart
#
# This program 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.
#
# 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 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.


"""Zip Archives Module"""


import os

import libxml2

import expression.core.directories as directories
import expression.core.environs as environs
import expression.core.filesystems as filesystems
import expression.core.namespaces as namespaces


class ZipHolder(directories.DirectoryHolder):
    _zipHolderInited = False
    defaultFileNameExtension = ".zip"
    mimeType = "application/zip"

    def __init__(self, node = None, *arguments, **keywords):
        if self._zipHolderInited:
            return
        self._zipHolderInited = True

        super(ZipHolder, self).__init__(*arguments, **keywords)
        self.containedFileSystem = filesystems.ZipFileSystem(
            self.fileSystem.open(self.getFileSystemPath(), "rb"))

    def doHttpDelete(self):
        # Ignore override of doHttpDelete method done in directories.DirectoryHolder.
        return super(directories.DirectoryHolder, self).doHttpDelete()

    def doHttpDelete1(self, multistatus):
        # Ignore override of doHttpDelete1 method done in directories.DirectoryHolder.
        return super(directories.DirectoryHolder, self).doHttpDelete1(multistatus)

    def doHttpGet(self):
        return self.source()

    def doHttpPut(self):
        # Ignore override of doHttpPut method done in directories.DirectoryHolder.
        return super(directories.DirectoryHolder, self).doHttpPut()

    def getSimplestSourceUrl(self):
        return self.getUri()

    def getSimplestStyledUrl(self):
        return self.getActionUri("styled")

    def getWebDavCollectionItems(self):
        raise NotImplementedError

    def getWebDavContentLength(self):
        dataFile = self.fileSystem.open(self.getFileSystemPath(), "rb")
        if hasattr(dataFile, "fileno"):
            dataSize = os.fstat(dataFile.fileno())[6]
        else:
            # For StringIO and cStringIO classes.
            dataSize = len(dataFile.getvalue())
        return dataSize

    def isWebDavCollection(self):
        return False

    def outputHttpSource(self):
        dataFile = self.fileSystem.open(self.getFileSystemPath(), "rb")
        environs.getVar("httpRequestHandler").outputData(
            dataFile, mimeType = self.mimeType, modificationTime = self.getModificationTime())

##     def setupDataHolder(self):
##         self.containedFileSystem = filesystems.ZipFileSystem(
##             self.fileSystem.open(self.getFileSystemPath(), "rb"))
##         if self.node is None:
##             if self.isRemote:
##                 raise Exception("FIXME, TODO: download data.")
##             else:
##                 indexFileSystemPath = os.path.join(
##                     self.getContainedFileSystemPath(), "index.xml")
##                 containedFileSystem = self.containedFileSystem
##                 if containedFileSystem.access(indexFileSystemPath, os.R_OK):
##                     dataFile = containedFileSystem.open(
##                         indexFileSystemPath, "rb")
##                     data = dataFile.read()
##                     dataFile.close()
##                 else:
##                     doc = libxml2.newDoc("1.0")
##                     rootNode = doc.newTextChild(None, "directory", None)
##                     namespace = rootNode.newNs(namespaces.yep.uri, None)
##                     rootNode.setNs(namespace)
##                     self.node = doc
##             if self.node is None:
##                 try:
##                     self.node = libxml2.readDoc(
##                         data, self.getAbsolutePath(), None,
##                         libxml2.XML_PARSE_DTDLOAD | libxml2.XML_PARSE_NONET)
##                 except (libxml2.parserError, libxml2.treeError):
##                     logs.info('Error while parsing XML file at "%s".' % self.getAbsolutePath())
##                     raise
##             self.publicName = self.localId
##             self.node.xincludeProcess()
##             #self.context = self.node.xpathNewContext()
##         self.setupXml()


ZipHolder.register()
