# 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

"""
Maintain WMS Capabilities

Inherits methods from WMSCapabilitiesParser

class WMSCapabilities:
    __init__ (resource xor filename xor nothing)

    getErrorMsg()

    fetchCapabilities(resource)
    saveCapabilities(filename)
    loadCapabilities(filename)
    printCapabilities()

    getVersion()

Requirements:
    - PyOGCLib <http://www.sourceforge.net/projects/pyogclib>

Requires the ogclib installed regularily on the system or checked out
next to the Thuban checkout.

If this module is executed solitarily, it will fetch the capabilities
of the frida service and store them in the local file
frida_capabilities.xml for later processing.

"""

__version__ = "$Revision: 1.9 $"
# $Source: /thubanrepository/thuban/Extensions/wms/capabilities.py,v $
# $Id: capabilities.py,v 1.9 2004/04/01 15:34:25 joey Exp $

import os

# ----------------------------------------------------------------------
# FIXME: Temporary code until PyOGCLib is a standard requirement

from sys import path

# Assume the PyOGCLib to be checked out next to the thuban main directory
pyogclib = "../../../PyOGCLib"
if os.path.isdir(pyogclib) and os.path.isdir(pyogclib + "/ogclib"):
    path.insert(0, pyogclib)

# We use gettext, so we need to import it and hence need to adjust the
# path again
if __name__ == "__main__":
    path.insert(0, "../../")

# ----------------------------------------------------------------------

from Thuban import _

from ogclib.WMSClient import WMSClient
from parser import WMSCapabilitiesParser

class WMSCapabilities(WMSClient, WMSCapabilitiesParser):
    """
    Thuban class to maintain capabilities.  This class provides
    methods to fetch, save and load capabilities as well as methods to
    retrieve particular information from the fetched or loaded
    capabilities XML.

    If an error occured during processing an error text is assigned to
    self.errorMsg.  If everything went fine, this variable is set to
    None.  The current value can be retrieved by the getErrorMsg()
    method.
    """

    capabilities = None
    errorMsg = None
    wmsVersion = None

    def __init__(self, *parm):
        """
        Initialises Capabilities with one optional parameter

        param can be either a URL or a filename:

        filename -- load capabilities from file
        url -- fetch capabilities from network
        """

        if parm and parm[0]:
            if os.path.isfile(parm[0]):
                self.loadCapabilities(parm[0])
            else:
                if parm[0].find("http://", 0) == 0:
                    self.fetchCapabilities(parm[0])
                else:
                    self.errorMsg \
                        = _("Resource '%s' is neither local file nor URL") \
                        % parm[0]


    def getErrorMsg(self):
        return self.errorMsg


    def fetchCapabilities(self, resource):
        """
        Fetches the WMS capabilities from an Internet resource

        WMS Protocol version 1.1 is tried first, then 1.0.  The
        protocol version used can be queried by the getVersion()
        method for later use.  If both tries fail, errorMsg will be
        set accordingly, which can be fetched with getErrorMsg().
        """

        self.wmsVersion = "1.1"
        self.capabilities = self.getCapabilities(resource, self.wmsVersion)
        if not self.capabilities:
            self.wmsVersion = "1.0"
            self.capabilities = self.getCapabilities(resource, self.wmsVersion)
            if not self.capabilities:
                self.wmsVersion = None
                self.errorMsg \
                    = _("Resource '%s' "
                        "does support neither WMS version 1.1 nor 1.0") \
                        % resource

        if self.capabilities:
            self.grok(self.capabilities)


    def saveCapabilities(self, fname):
        """Save capabilities to local file"""

        if self.capabilities is None:
            self.errorMsg = _("No capabilities available")
        else:
            try:
                out = open(fname, "w")
                out.write(self.capabilities)
                out.close()
            except IOError:
                self.errorMsg = _("Can't open file '%s' for writing") % fname


    def loadCapabilities(self, fname):
        """Load capabilities from a local file"""

        try:
            input = open(fname, "r")
            self.capabilities = input.read()
            input.close()
            self.grok(self.capabilities)
        except IOError:
            self.errorMsg = _("Can't open file '%s' for reading") % fname


    def printCapabilities(self):
        """Prints capabilities to stdout"""

        print self.capabilities


    def getVersion(self):
        """
        Returns the WMS protocol version

        If no capabilities could be fetched, None is returned.
        """
        return self.wmsVersion


if __name__ == "__main__":
    capabilities \
        = WMSCapabilities("http://frida.intevation.org/cgi-bin/frida_wms?")
    if capabilities.getErrorMsg() is None:
        capabilities.saveCapabilities("frida_capabilities.xml")
    else:
        print "Error: " + capabilities.getErrorMsg()
