# -*- 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.


"""Configuration Files Module"""


import os

import dataholders
import elements
import environs
import logs
import namespaces
import things


class Configuration(things.Thing):
    def getAllConfigElementNodesAndOwnerCouples(self, xpath):
        relevantNodesAndOwnerCouples = {}
        elementNodes = self.evaluateXpath("yep:element")
        for elementNode in elementNodes:
            nodes = self.evaluateXpath(xpath, contextNode = elementNode)
            if not nodes:
                continue
            nameNodes = self.evaluateXpath("@name", contextNode = elementNode)
            if not nameNodes:
                continue
            name = nameNodes[0].content
            namespaceUriNodes = self.evaluateXpath("@namespace", contextNode = elementNode)
            if not namespaceUriNodes:
                continue
            namespaceUri = namespaceUriNodes[0].content
            key = "%s / %s" % (namespaceUri, name)
            relevantNodesAndOwnerCouples[key] = (nodes, self)
        return relevantNodesAndOwnerCouples

    def getConfigDataHolderNodesAndOwner(self, mimeType, xpath, ignoreGeneralValue = False):
        dataHolderNodes = self.evaluateXpath("yep:inode[@mimeType = '%s']" %  mimeType.replace(
            "'", "&apos;"))
        if dataHolderNodes:
            dataHolderNode = dataHolderNodes[0]
            nodes = self.evaluateXpath(xpath, contextNode = dataHolderNode)
            if nodes:
                return nodes, self
        if not ignoreGeneralValue:
            return self.evaluateXpath(xpath), self
        return [], self

    def getConfigElementNodesAndOwner(self, namespaceUri, name, xpath, ignoreGeneralValue = False):
        if namespaceUri is None:
            return [], self
        elementNodes = self.evaluateXpath("yep:element[@namespace = '%s' and @name = '%s']" % (
            namespaceUri.replace("'", "&apos;"), name.replace("'", "&apos;")))
        if elementNodes:
            elementNode = elementNodes[0]
            nodes = self.evaluateXpath(xpath, contextNode = elementNode)
            if nodes:
                return nodes, self
        if not ignoreGeneralValue:
            return self.evaluateXpath(xpath), self
        return [], self

    def getConfigStationNodesAndOwner(self, xpath):
        return self.evaluateXpath(xpath), self

    def getItemLocations(self):
        itemLocations = {}
        itemNodes = self.evaluateXpath("yep:item")
        for itemNode in itemNodes:
            nameNodes = self.evaluateXpath("@name", itemNode)
            if not nameNodes:
                logs.info("""Missing attribute "name" in item "%s".""" %
                          itemNode.serialize())
                continue
            name = nameNodes[0].content.strip()
            locationNodes = self.evaluateXpath("@src", itemNode)
            if locationNodes:
                location = locationNodes[0].content.strip()
            else:
                location = name
            location = self.convertPathToAbsolute(location)
            itemLocations[name] = location
        return itemLocations

    def getLocales(self):
        for node in self.evaluateXpath("yep:locales"):
            if node.content:
                return node.content.split(" ")
        return []

    def getLocalesPath(self):
        for node in self.evaluateXpath("yep:localesPath"):
            return node.content

    def getPythonAbsolutePaths(self):
        nodes = self.evaluateXpath("yep:pythonPath")
        return [self.convertPathToAbsolute(node.content.strip()) for node in nodes]

    def getPythonModuleNames(self):
        nodes = self.evaluateXpath("yep:module/@name")
        return [node.content for node in nodes]

    def getVirtualHosts(self):
        # FIXME: Change previous, parent, uriPathFragment?
        return VirtualHosts(
            self.node, previous = self.previous, parent = self._parent,
            uriPathFragment = self.uriPathFragment, owner = self)


class VirtualHost(elements.Element):
    accessLogFile = None
    brotherVirtualHost = None
        # The SSL virtual host corresponding to this non SSL virtual host, or
        # the opposite.
    isSsl = False

    def getAllConfigElementNodesAndOwnerCouples(self, xpath):
        relevantNodesAndOwnerCouples = environs.getVar(
            "configuration").getAllConfigElementNodesAndOwnerCouples(xpath)
        elementNodes = self.evaluateXpath("yep:element")
        for elementNode in elementNodes:
            nodes = self.evaluateXpath(xpath, contextNode = elementNode)
            if not nodes:
                continue
            nameNodes = self.evaluateXpath("@name", contextNode = elementNode)
            if not nameNodes:
                continue
            name = nameNodes[0].content
            namespaceUriNodes = self.evaluateXpath("@namespace", contextNode = elementNode)
            if not namespaceUriNodes:
                continue
            namespaceUri = namespaceUriNodes[0].content
            key = "%s / %s" % (namespaceUri, name)
            relevantNodesAndOwnerCouples[key] = (nodes, self)
        return relevantNodesAndOwnerCouples

    def getConfigDataHolderNodesAndOwner(self, mimeType, xpath, ignoreGeneralValue = False):
        dataHolderNodes = self.evaluateXpath("yep:inode[@mimeType = '%s']" %  mimeType.replace(
            "'", "&apos;"))
        if dataHolderNodes:
            dataHolderNode = dataHolderNodes[0]
            nodes = self.evaluateXpath(xpath, contextNode = dataHolderNode)
            if nodes:
                return nodes, self
        if not ignoreGeneralValue:
            nodes = self.evaluateXpath(xpath)
            if nodes:
                return nodes, self
        return environs.getVar("configuration").getConfigDataHolderNodesAndOwner(
            mimeType, xpath, ignoreGeneralValue = ignoreGeneralValue)

    def getConfigElementNodesAndOwner(self, namespaceUri, name, xpath, ignoreGeneralValue = False):
        if namespaceUri is None:
            return [], self
        elementNodes = self.evaluateXpath("yep:element[@namespace = '%s' and @name = '%s']" % (
            namespaceUri.replace("'", "&apos;"), name.replace("'", "&apos;")))
        if elementNodes:
            elementNode = elementNodes[0]
            nodes = self.evaluateXpath(xpath, contextNode = elementNode)
            if nodes:
                return nodes, self
        if not ignoreGeneralValue:
            nodes = self.evaluateXpath(xpath)
            if nodes:
                return nodes, self
        return environs.getVar("configuration").getConfigElementNodesAndOwner(
            namespaceUri, name, xpath, ignoreGeneralValue = ignoreGeneralValue)

    def getConfigStationNodesAndOwner(self, xpath):
        nodes = self.evaluateXpath(xpath)
        if nodes:
            return nodes, self
        return environs.getVar("configuration").getConfigStationNodesAndOwner(xpath)

    def getDomains(self):
        for node in self.evaluateXpath("yep:domains"):
            if node.content:
                return node.content.split(" ")
        return []

    def getIpAddress(self):
        nodes = self.evaluateXpath("yep:ip")
        if nodes:
            return nodes[0].content.strip()
        else:
            return ""

    def getItemLocations(self):
        itemLocations = environs.getVar("configuration").getItemLocations()
        itemNodes = self.evaluateXpath("yep:item")
        for itemNode in itemNodes:
            nameNodes = self.evaluateXpath("@name", itemNode)
            if not nameNodes:
                logs.info("""Missing attribute "name" in item "%s".""" %
                          itemNode.serialize())
                continue
            name = nameNodes[0].content.strip()
            locationNodes = self.evaluateXpath("@src", itemNode)
            if locationNodes:
                location = locationNodes[0].content.strip()
            else:
                location = name
            location = self.convertPathToAbsolute(location)
            itemLocations[name] = location
        return itemLocations

    def getPort(self):
        nodes = self.evaluateXpath("yep:port")
        if nodes:
            return int(nodes[0].content.strip())
        else:
            return None

    def getServerName(self):
        nodes = self.evaluateXpath("yep:serverName")
        if nodes:
            return nodes[0].content.strip()
        else:
            return None

    def getServerAliases(self):
        nodes = self.evaluateXpath("yep:serverAlias")
        return [x.content.strip() for x in nodes]


class SslVirtualHost(VirtualHost):
    isSsl = True


class VirtualHosts(elements.List):
    itemsXpath = "yep:virtualHost | yep:sslVirtualHost"


elements.registerElement(namespaces.yep.uri, "configuration", Configuration)
elements.registerElement(namespaces.yep.uri, "sslVirtualHost", SslVirtualHost)
elements.registerElement(namespaces.yep.uri, "virtualHost", VirtualHost)
