# Copyright (c) 2004 by Intevation GmbH
# Authors:
# Martin Schulze <joey@infodrom.org>
#
# 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

"""
Inspect WMS Capabilities for later processing.

Information should only be retrieved with the proper get*() methods.

class WMSCapabilitiesParser:
    __init__()

    grok(string)

    getTitle()
    getAbstract()
    getFees()
    getAccessConstraints()
    getFormats()
    getLayers()
    getSRS()

    getLayerTitle(layer)
    getLayerSRS(layer)
    getLayerLatLonBBox(layer)
    getLayerBBox(layer, srs)

    isQueryable(layer)
"""

__version__ = "$Revision: 2439 $"
# $Source$
# $Id: parser.py 2439 2004-12-09 10:37:44Z joey $

import xml.dom.minidom
from xml.dom import Node

from domutils import getElementsByName, getElementByName

from Thuban import _

class WMSCapabilitiesParser:
    """
    Thuban class to parse capabilities supplied as large string.

    This class provides methods to parse and retrieve particular
    information from the WMS capabilities XML.  Information should
    only be extracted by the respective get*() methods.
    """

    layers = None
    title = None
    abstract = None
    fees = None
    access = None
    formats = None
    error = None


    def __init__(self):
        """
        Initialises an instance in this class.
        """

        # Note that we must not initialise internal variables of the
        # class in a mutable way or it will be shared among all
        # instances.  None is immutable, [] is not.
        self.error = []


    def grok(self, data):
        """
        Parses the XML response to a WMS GetCapabilities request.

        Internal datastructure of the class will be filled.
        Information should only be retrieved with the respective
        get*() methods.
        """
        xml_dom = xml.dom.minidom.parseString(data)
        root = xml_dom.documentElement

        # Extract the title
        foo = getElementByName(getElementByName(root, 'Service'), 'Title')
        if foo:
            self.title = foo.childNodes[0].data
        
        # Extract the abstract
        foo = getElementByName(getElementByName(root, 'Service'), 'Abstract')
        if foo and len(foo.childNodes[0].data):
            self.abstract = foo.childNodes[0].data
        
        # Extract fees information
        foo = getElementByName(getElementByName(root, 'Service'), 'Fees')
        if foo and len(foo.childNodes[0].data) \
               and foo.childNodes[0].data.lower() != 'none':
            self.fees = foo.childNodes[0].data
        
        # Extract access information
        foo = getElementByName(getElementByName(root, 'Service'),
                               'AccessConstraints')
        if foo and len(foo.childNodes[0].data) \
               and foo.childNodes[0].data.lower() != 'none':
            self.access = foo.childNodes[0].data
        
        foo = getElementByName(getElementByName(
            root, 'Capability'), 'Request')

        # Need to distinguish between Map and GetMap for v1.0 and v1.1
        bar = getElementByName(foo, 'GetMap')
        if bar:
            # WMS 1.1
            foo = getElementsByName(bar, 'Format')
            self.formats = map((lambda i: i.childNodes[0].data), foo)
        else:
            # WMS 1.0
            foo = getElementByName(getElementByName(
                foo, 'Map'), 'Format')
            for node in foo.childNodes:
                if node.nodeType == Node.ELEMENT_NODE:
                    try:
                        self.formats.append(node.nodeName)
                    except AttributeError:
                        self.formats = [node.nodeName]

        # Extract layer names
        self.layers = []
        self.peekLayers(getElementByName(getElementByName(
            root, 'Capability'), 'Layer'), -1)

        xml_dom.unlink()


    def peekLayers(self, top, parent):
        """
        Inspect the provided DOM fragment referenced as top.

        This method will inspect all included layers and traverse the
        tree recursively in order to fill the internal datastructure.

        Note that SRS other than EPSG:* are not yet supported,
        especially there is no support for AUTO and NONE.
        """

        index = len (self.layers)
        self.layers.append({})
        self.layers[index]['parent'] = parent

        for foo in top.attributes.keys():
            if foo == 'queryable':
                self.layers[index]['queryable'] \
                    = int(top.attributes.get(foo).nodeValue)

        foo = getElementByName(top, 'Title')
        if foo and len(foo.childNodes[0].data):
            self.layers[index]['title'] = foo.childNodes[0].data
        else:
            # A <Title> is required for each layer, <name> is optional
            # See OGC 01-068r3, 7.1.4.5.1 and 7.1.4.5.2
            self.error.append(_("No title found for layer #%d") % index)

        foo = getElementByName(top, 'Name')
        if foo and len(foo.childNodes[0].data):
            self.layers[index]['name'] = foo.childNodes[0].data

        # These values are only used for an integrity check
        for foo in getElementsByName(top, 'SRS'):
            for srs in foo.childNodes[0].data.split(" "):
                if srs[0:5] == 'EPSG:':
                    srs = srs[5:]
                try:
                    int(srs)
                    try:
                        self.layers[index]['srs'].append(srs)
                    except KeyError:
                        self.layers[index]['srs'] = [srs]
                except ValueError:
                    if srs[0:4].upper() == 'AUTO' \
                           or srs[0:4].upper() == 'NONE':
                        try:
                            self.layers[index]['_srs_'].append(srs)
                        except KeyError:
                            self.layers[index]['_srs_'] = [srs]
                    else:
                        self.error.append(_("SRS '%s' is not numerical and not"
                                            " AUTO/NONE in layer '%s'") \
                                          % (srs, self.layers[index]['title']))

        foo = getElementByName(top, 'LatLonBoundingBox')
        if foo is not None:
            self.layers[index]['llbbox'] = {}
            for corner in ['minx', 'miny', 'maxx', 'maxy']:
                self.layers[index]['llbbox'][corner] \
                    = foo.attributes.get(corner).nodeValue

        boxes = getElementsByName(top, 'BoundingBox')
        if boxes != []:
            self.layers[index]['bbox'] = {}
        for foo in boxes:
            srs = foo.attributes.get('SRS').nodeValue
            if srs[0:5] == 'EPSG:':
                srs = srs[5:]
            self.layers[index]['bbox'][srs] = {}
            for corner in ['minx', 'miny', 'maxx', 'maxy']:
                self.layers[index]['bbox'][srs][corner] \
                    = foo.attributes.get(corner).nodeValue
            
        # Traverse subsidiary layers
        sublayer = getElementsByName(top, 'Layer')
        for l in sublayer:
            self.peekLayers(l, index)


    def getTitle(self):
        """
        Returns the main title of the WMS object.

        If no title is provided in the capabilities, an empty string
        is returned.
        """
        if self.title is None:
            return ''
        else:
            return self.title


    def getAbstract(self):
        """
        Returns the abstract of the WMS object.

        If no abstract is provided in the capabilities, an empty
        string is returned.
        """
        if self.abstract is None:
            return ''
        else:
            return self.abstract


    def getFees(self):
        """
        Returns the fees information of the WMS object.

        If no information is provided in the capabilities or if it is
        set to 'none', an empty string is returned.
        """
        if self.fees is None:
            return ''
        else:
            return self.fees


    def getAccessConstraints(self):
        """
        Returns information about access constraints for the WMS object.

        If no information is provided in the capabilities or if it is
        set to 'none', an empty string is returned.
        """
        if self.access is None:
            return ''
        else:
            return self.access


    def getFormats(self):
        """
        Returns a list of supported output formats.

        These are used in the GetMap request.  This method will
        default to 'image/jpeg' if no format is recognised in XML
        Capabilities, assuming that JPEG will always be supported on
        the server side.
        """
        if self.formats is None:
            return ['image/jpeg']
        else:
            return self.formats

    def getLayers(self):
        """
        Returns a list of layer names.

        Only named layers will be returned, since a layer may have a
        title but doesn't have to have a name associated to it as
        well.  If no layers were found, an empty list is returned.
        """
        result = []
        for layer in self.layers:
            if 'name' in layer:
                result.append(layer['name'])

        return result


    def getSRS(self):
        """
        Returns the root list of spatial reference systems (SRS).

        This list is taken from the root layer.  Those SRS are common
        to all subsidiary layers.  If no SRS are common to all layers,
        an empty list is returned.  If no layers were detected, an
        empty list is returned as well.
        """
        if len(self.layers) == 0:
            return []

        # index 0 denotes the root layer by design
        if 'srs' in self.layers[0].keys():
            return self.layers[0]['srs']


    def getLayerTitle(self, name):
        """
        Returns the title of the named layer.

        If no such title or no such layer exists, an empty string is
        returned.
        """
        for layer in self.layers:
            if 'name' in layer:
                if layer['name'] == name:
                    if 'title' in layer:
                        return layer['title']

        return ''


    def getLayerSRS(self, name):
        """
        Returns a list of spacial reference systems (SRS).

        The SRS are specified by the European Petroleum Survey Group
        (EPSG).  There should be at least one SRS per layer, though.
        The prefix 'EPSG:' will be stripped.  If none exists, an empty
        list is returned.

        The specification [OGC 01-068r3] says about inheritance of
        SRS:

        - Every layer is available in one or more SRS (or in an
          undefined SRS)

        - Geographic information whose SRS is undefined
          (e.g. digitised historical maps) shall use 'NONE'
          (case-sensitive).  This implementation does not support
          this.

        - Every layer shall have at least one SRS element that is
          either stated explicitly or inherited from a parent layer.

        - The root layer element shall include a sequence of zero or
          more SRS elements listing all SRS which are common for to
          all subsidiary layers.

        - Layers may optionally add to the global SRS list, or to the
          list inherited from a parent layer.

        - A server which has the ability to transform data to
          different SRSes may choose not to provide an explicit
          BoundingBox for every possible SRS available for each Layer.
          Thus the list of <SRS> elements are authoritative.

        This implementation returns the list of SRS for the given
        layer, calculated by looking at BoundingBoxes defined in the
        named layer and all layers higher in the hierarchy up to the
        root layer which weren't overwritten.
        """
        for i in range(len(self.layers)):
            if 'name' in self.layers[i]:
                if self.layers[i]['name'] == name:
                    pivot = i
                    break
        else:
            return []

        result = []
        while pivot != -1:
            if 'srs' in self.layers[pivot]:
                for srs in self.layers[pivot]['srs']:
                    if srs not in result:
                        result.append(srs)
            pivot = self.layers[pivot]['parent']

        return result


    def getLayerLatLonBBox(self, name):
        """
        Returns a dictionary of the LatLonBoundingBox.

        ... for the named layer if it exists.  The SRS is always
        EPSG:4326 per convention.  There should be at least one,
        though, inherited from the root layer at least.  If none
        exists, the value None is returned.
        """
        for layer in self.layers:
            if 'name' in layer:
                if layer['name'] == name:
                    if 'llbbox' in layer:
                        return layer['llbbox']
                    else:
                        # No LatLonBoundingBox found in current layer,
                        # so traverse the hierarchy upwards and check
                        # again until there is one.
                        pivot = layer
                        while pivot['parent'] != -1:
                            pivot = self.layers[pivot['parent']]
                            if 'llbbox' in pivot:
                                return pivot['llbbox']

        return None


    def getLayerBBox(self, name, srs):
        """
        Returns a dictionary of the BoundingBox.

        If no such BoundingBox exists, None is returned.

        The specification [OGC 01-068r3] says about BoundingBoxes:

        - Layers may have zero or more BoundingBox elements what are
          either stated explicitly or inherited from a parent layer.

        - A layer may have multiple BoundingBox elements, but each one
          shall state a different SRS.

        - A layer inherits any BoundingBoxes defined by its
          parents.

        - A BoundingBox inherited from the parent layer for a
          particular SRS is replaced by any declaration for the same
          SRS in the current layer.

        - A BoundingBox in the child layer for a new SRS which is not
          already declared by the parent, is added to the list of
          BoundingBoxes for the child layer.

        - A single layer shall not contain more than one BoundingBox
          element for the same SRS.
        """
        for layer in self.layers:
            if 'name' in layer:
                if layer['name'] == name:
                    if 'bbox' in layer:
                        if srs in layer['bbox']:
                            return layer['bbox'][srs]
                    
                    # No BoundingBox for the given SRS found in
                    # current layer, so traverse the hierarchy upwards
                    # and check again until there is one.
                    pivot = layer
                    while pivot['parent'] != -1:
                        pivot = self.layers[pivot['parent']]
                        if 'bbox' in pivot:
                            if srs in pivot['bbox']:
                                return pivot['bbox'][srs]

        # No matching BBox found, let's see if it was EPSG:4326
        if srs == '4326':
            return self.getLayerLatLonBBox(name)

        return None


    def isQueryable(self, name):
        """
        Returns the value of the queryable attribute of a layer.

        This attribute denotes whether this layer can be queried
        through the GetFeatureInfo request.  The default value is 0.

        The specification [OGC 01-068r3] this attribute can be
        inherited.
        """

        for layer in self.layers:
            if 'name' in layer:
                if layer['name'] == name:
                    try:
                        return layer['queryable']
                    except KeyError:
                        # No attribute in this layer, so traverse the
                        # hierarchy upwards
                        pivot = layer
                        while pivot['parent'] != -1:
                            pivot = self.layers[pivot['parent']]
                            if 'queryable' in pivot:
                                return pivot['queryable']
        return 0



if __name__ == "__main__":
    print "This module cannot be executed standalone."

    import os

    sample = "test/sample.xml"
    try:
        f = open(sample, "r")
    except IOError:
        try:
            f = open(os.path.dirname(__file__) + "/" + sample, "r")
        except IOError:
            print "Cannot open %s for reading" % sample

    if f is not None:
        sample = f.read();
        f.close()
        
        ina = WMSCapabilitiesParser()
        ina.grok(sample)
