# Copyright (C) 2001, 2002, 2003 by Intevation GmbH
# Authors:
# Jan-Oliver Wagner <jan@intevation.de>
# Bernhard Herzog <bh@intevation.de>
# Jonathan Coles <jonathan@intevation.de>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with GRASS for details.

"""
Parser for thuban session files.
"""

__version__ = "$Revision: 1.45 $"

import string, os

import xml.sax
import xml.sax.handler
from xml.sax import make_parser, ErrorHandler, SAXNotRecognizedException

from Thuban import _

from Thuban.Model.table import FIELDTYPE_INT, FIELDTYPE_DOUBLE, \
     FIELDTYPE_STRING

from Thuban.Model.color import Color, Transparent

from Thuban.Model.session import Session
from Thuban.Model.map import Map
from Thuban.Model.layer import Layer, RasterLayer
from Thuban.Model.proj import Projection
from Thuban.Model.range import Range
from Thuban.Model.classification import Classification, \
    ClassGroupDefault, ClassGroupSingleton, ClassGroupRange, ClassGroupMap, \
    ClassGroupProperties
from Thuban.Model.data import DerivedShapeStore, ShapefileStore
from Thuban.Model.table import DBFTable
from Thuban.Model.transientdb import TransientJoinedTable

from Thuban.Model.xmlreader import XMLReader
import resource

import postgisdb

class LoadError(Exception):

    """Exception raised when the thuban file is corrupted

    Not all cases of corrupted thuban files will lead to this exception
    but those that are found by checks in the loading code itself are. 
    """


class LoadCancelled(Exception):

    """Exception raised to indicate that loading was interrupted by the user"""


def parse_color(color):
    """Return the color object for the string color.

    Color may be either 'None' or of the form '#RRGGBB' in the usual
    HTML color notation
    """
    color = string.strip(color)
    if color == "None":
        result = Transparent
    elif color[0] == '#':
        if len(color) == 7:
            r = string.atoi(color[1:3], 16) / 255.0
            g = string.atoi(color[3:5], 16) / 255.0
            b = string.atoi(color[5:7], 16) / 255.0
            result = Color(r, g, b)
        else:
            raise ValueError(_("Invalid hexadecimal color specification %s")
                             % color)
    else:
        raise ValueError(_("Invalid color specification %s") % color)
    return result

class AttrDesc:

    def __init__(self, name, required = False, default = "",
                 conversion = None):
        if not isinstance(name, tuple):
            fullname = (None, name)
        else:
            fullname = name
            name = name[1]
        self.name = name
        self.fullname = fullname
        self.required = required
        self.default = default
        self.conversion = conversion

        # set by the SessionLoader's check_attrs method
        self.value = None


class SessionLoader(XMLReader):

    def __init__(self, db_connection_callback = None):
        """Inititialize the Sax handler."""
        XMLReader.__init__(self)

        self.db_connection_callback = db_connection_callback

        self.theSession = None
        self.aMap = None
        self.aLayer = None

        # Map ids used in the thuban file to the corresponding objects
        # in the session
        self.idmap = {}

        dispatchers = {
            'session'       : ("start_session",        "end_session"),

            'dbconnection': ("start_dbconnection", None),

            'dbshapesource': ("start_dbshapesource", None),
            'fileshapesource': ("start_fileshapesource", None),
            'derivedshapesource': ("start_derivedshapesource", None),
            'filetable': ("start_filetable", None),
            'jointable': ("start_jointable", None),

            'map'           : ("start_map",            "end_map"),
            'projection'    : ("start_projection",     "end_projection"),
            'parameter'     : ("start_parameter",      None),
            'layer'         : ("start_layer",          "end_layer"),
            'rasterlayer'   : ("start_rasterlayer",    "end_rasterlayer"),
            'classification': ("start_classification", "end_classification"),
            'clnull'        : ("start_clnull",         "end_clnull"),
            'clpoint'       : ("start_clpoint",        "end_clpoint"),
            'clrange'       : ("start_clrange",        "end_clrange"),
            'cldata'        : ("start_cldata",         "end_cldata"),
            'table'         : ("start_table",          "end_table"),
            'labellayer'    : ("start_labellayer",     None),
            'label'         : ("start_label",          None)}

        # all dispatchers should be used for the 0.8 and 0.9 namespaces too
        for xmlns in ("http://thuban.intevation.org/dtds/thuban-0.8.dtd",
                      "http://thuban.intevation.org/dtds/thuban-0.9-dev.dtd",
                      "http://thuban.intevation.org/dtds/thuban-0.9.dtd",
                      "http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd",
                      "http://thuban.intevation.org/dtds/thuban-1.0rc1.dtd"):
            for key, value in dispatchers.items():
                dispatchers[(xmlns, key)] = value

        XMLReader.AddDispatchers(self, dispatchers)

    def Destroy(self):
        """Clear all instance variables to cut cyclic references.

        The GC would have collected the loader eventually but it can
	happen that it doesn't run at all until Thuban is closed (2.3
	but not 2.2 tries a bit harder and forces a collection when the
	interpreter terminates)
        """
        self.__dict__.clear()

    def start_session(self, name, qname, attrs):
        self.theSession = Session(self.encode(attrs.get((None, 'title'),
                                                        None)))

    def end_session(self, name, qname):
        pass

    def check_attrs(self, element, attrs, descr):
        """Check and convert some of the attributes of an element

        Parameters:
           element -- The element name
           attrs -- The attrs mapping as passed to the start_* methods
           descr -- Sequence of attribute descriptions (AttrDesc instances)

        Return a dictionary containig normalized versions of the
        attributes described in descr. The keys of that dictionary are
        the name attributes of the attribute descriptions. The attrs
        dictionary will not be modified.

        If the attribute is required, i.e. the 'required' attribute of
        the descrtiption is true, but it is not in attrs, raise a
        LoadError.

        If the attribute has a default value and it is not present in
        attrs, use that default value as the value in the returned dict.

        The value is converted before putting it into the returned dict.
        The following conversions are available:

           'filename' -- The attribute is a filename.

                         If the filename is a relative name, interpret
                         it relative to the directory containing the
                         .thuban file and make it an absolute name

           'shapestore' -- The attribute is the ID of a shapestore
                           defined earlier in the .thuban file. Look it
                           up self.idmap

           'table' -- The attribute is the ID of a table or shapestore
                      defined earlier in the .thuban file. Look it up
                      self.idmap. If it's the ID of a shapestore the
                      value will be the table of the shapestore.

           'idref' -- The attribute is the id of an object defined
                      earlier in the .thuban file. Look it up self.idmap

           'ascii' -- The attribute is converted to a bytestring with
                      ascii encoding.

           a callable -- The attribute value is passed to the callable
                         and the return value is used as the converted
                         value

        If no conversion is specified for an attribute it is converted
        with self.encode.
        """
        normalized = {}

        for d in descr:
            if d.required and not attrs.has_key(d.fullname):
                raise LoadError("Element %s requires an attribute %r"
                                % (element, d.name))
            value = attrs.get(d.fullname, d.default)

            if d.conversion in ("idref", "shapesource"):
                if value in self.idmap:
                    value = self.idmap[value]
                else:
                    raise LoadError("Element %s requires an already defined ID"
                                    " in attribute %r"
                                    % (element, d.name))
            elif d.conversion == "table":
                if value in self.idmap:
                    value = self.idmap[value]
                    if isinstance(value, ShapefileStore):
                        value = value.Table()
                else:
                    raise LoadError("Element %s requires an already defined ID"
                                    " in attribute %r"
                                    % (element, d.name))
            elif d.conversion == "filename":
                value = os.path.abspath(os.path.join(self.GetDirectory(),
                                                     value))
            elif d.conversion == "ascii":
                value = value.encode("ascii")
            elif d.conversion:
                # Assume it's a callable
                value = d.conversion(value)
            else:
               value = self.encode(value)

            normalized[d.name] = value
        return normalized

    def start_dbconnection(self, name, qname, attrs):
        attrs = self.check_attrs(name, attrs,
                                 [AttrDesc("id", True),
                                  AttrDesc("dbtype", True),
                                  AttrDesc("host", False, ""),
                                  AttrDesc("port", False, ""),
                                  AttrDesc("user", False, ""),
                                  AttrDesc("dbname", True)])
        ID = attrs["id"]
        dbtype = attrs["dbtype"]
        if dbtype != "postgis":
            raise LoadError("dbtype %r not supported" % filetype)

        del attrs["id"]
        del attrs["dbtype"]

        # Try to open the connection and if it fails ask the user for
        # the correct parameters repeatedly.
        # FIXME: it would be better not to insist on getting a
        # connection here. We should handle this more like the raster
        # images where the layers etc still are created but are not
        # drawn in case Thuban can't use the data for various reasons
        while 1:
            try:
                conn = postgisdb.PostGISConnection(**attrs)
                break
            except postgisdb.ConnectionError, val:
                if self.db_connection_callback is not None:
                    attrs = self.db_connection_callback(attrs, str(val))
                    if attrs is None:
                        raise LoadCancelled
                else:
                    raise

        self.idmap[ID] = conn
        self.theSession.AddDBConnection(conn)

    def start_dbshapesource(self, name, qname, attrs):
        attrs = self.check_attrs(name, attrs,
                                 [AttrDesc("id", True),
                                  AttrDesc("dbconn", True,
                                           conversion = "idref"),
                                  AttrDesc("tablename", True,
                                           conversion = "ascii")])
        ID = attrs["id"]
        db = attrs["dbconn"]
        tablename = attrs["tablename"]
        self.idmap[ID] = self.theSession.OpenDBShapeStore(db, tablename)

    def start_fileshapesource(self, name, qname, attrs):
        attrs = self.check_attrs(name, attrs,
                                  [AttrDesc("id", True),
                                   AttrDesc("filename", True,
                                            conversion = "filename"),
                                   AttrDesc("filetype", True)])
        ID = attrs["id"]
        filename = attrs["filename"]
        filetype = attrs["filetype"]
        if filetype != "shapefile":
            raise LoadError("shapesource filetype %r not supported" % filetype)
        self.idmap[ID] = self.theSession.OpenShapefile(filename)

    def start_derivedshapesource(self, name, qname, attrs):
        attrs = self.check_attrs(name, attrs,
                                 [AttrDesc("id", True),
                                  AttrDesc("shapesource", True,
                                           conversion = "shapesource"),
                                  AttrDesc("table", True, conversion="table")])
        store = DerivedShapeStore(attrs["shapesource"], attrs["table"])
        self.theSession.AddShapeStore(store)
        self.idmap[attrs["id"]] = store

    def start_filetable(self, name, qname, attrs):
        attrs = self.check_attrs(name, attrs,
                                 [AttrDesc("id", True),
                                  AttrDesc("title", True),
                                  AttrDesc("filename", True,
                                           conversion = "filename"),
                                  AttrDesc("filetype")])
        filetype = attrs["filetype"]
        if filetype != "DBF":
            raise LoadError("shapesource filetype %r not supported" % filetype)
        table = DBFTable(attrs["filename"])
        table.SetTitle(attrs["title"])
        self.idmap[attrs["id"]] = self.theSession.AddTable(table)

    def start_jointable(self, name, qname, attrs):
        attrs = self.check_attrs(name, attrs,
                                 [AttrDesc("id", True),
                                  AttrDesc("title", True),
                                  AttrDesc("left", True, conversion="table"),
                                  AttrDesc("leftcolumn", True),
                                  AttrDesc("right", True, conversion="table"),
                                  AttrDesc("rightcolumn", True),

                                  # jointype is required for file
                                  # version 0.9 but this attribute
                                  # wasn't in the 0.8 version because of
                                  # an oversight so we assume it's
                                  # optional since we want to handle
                                  # both file format versions here.
                                  AttrDesc("jointype", False,
                                           default="INNER")])

        jointype = attrs["jointype"]
        if jointype == "LEFT OUTER":
            outer_join = True
        elif jointype == "INNER":
            outer_join = False
        else:
            raise LoadError("jointype %r not supported" % jointype )
        table = TransientJoinedTable(self.theSession.TransientDB(),
                                     attrs["left"], attrs["leftcolumn"],
                                     attrs["right"], attrs["rightcolumn"],
                                     outer_join = outer_join)
        table.SetTitle(attrs["title"])
        self.idmap[attrs["id"]] = self.theSession.AddTable(table)

    def start_map(self, name, qname, attrs):
        """Start a map."""
        self.aMap = Map(self.encode(attrs.get((None, 'title'), None)))

    def end_map(self, name, qname):
        self.theSession.AddMap(self.aMap)
        self.aMap = None

    def start_projection(self, name, qname, attrs):
        attrs = self.check_attrs(name, attrs,
                                 [AttrDesc("name", conversion=self.encode),
                                  AttrDesc("epsg", default=None,
                                           conversion=self.encode)])
        self.projection_name = attrs["name"]
        self.projection_epsg = attrs["epsg"]
        self.projection_params = [ ]

    def end_projection(self, name, qname):
        if self.aLayer is not None:
            obj = self.aLayer
        elif self.aMap is not None:
            obj = self.aMap
        else:
            assert False, "projection tag out of context"
            pass

        obj.SetProjection(Projection(self.projection_params,
                                     self.projection_name,
                                     epsg = self.projection_epsg))

    def start_parameter(self, name, qname, attrs):
        s = attrs.get((None, 'value'))
        s = str(s) # we can't handle unicode in proj
        self.projection_params.append(s)

    def start_layer(self, name, qname, attrs, layer_class = Layer):
        """Start a layer

        Instantiate a layer of class layer_class from the attributes in
        attrs which may be a dictionary as well as the normal SAX attrs
        object and bind it to self.aLayer.
        """
        title = self.encode(attrs.get((None, 'title'), ""))
        filename = attrs.get((None, 'filename'), "")
        filename = os.path.join(self.GetDirectory(), filename)
        filename = self.encode(filename)
        visible  = self.encode(attrs.get((None, 'visible'), "true")) != "false"
        fill = parse_color(attrs.get((None, 'fill'), "None"))
        stroke = parse_color(attrs.get((None, 'stroke'), "#000000"))
        stroke_width = int(attrs.get((None, 'stroke_width'), "1"))
        if attrs.has_key((None, "shapestore")):
            store = self.idmap[attrs[(None, "shapestore")]]
        else:
            store = self.theSession.OpenShapefile(filename)
        self.aLayer = layer_class(title, store,
                                  fill = fill, stroke = stroke,
                                  lineWidth = stroke_width,
                                  visible = visible)

    def end_layer(self, name, qname):
        self.aMap.AddLayer(self.aLayer)
        self.aLayer = None

    def start_rasterlayer(self, name, qname, attrs, layer_class = RasterLayer):
        title = self.encode(attrs.get((None, 'title'), ""))
        filename = attrs.get((None, 'filename'), "")
        filename = os.path.join(self.GetDirectory(), filename)
        filename = self.encode(filename)
        visible  = self.encode(attrs.get((None, 'visible'), "true")) != "false"

        self.aLayer = layer_class(title, filename, visible = visible)

    def end_rasterlayer(self, name, qname):
        self.aMap.AddLayer(self.aLayer)
        self.aLayer = None

    def start_classification(self, name, qname, attrs):
        attrs = self.check_attrs(name, attrs,
                                 [AttrDesc("field", True),
                                  AttrDesc("field_type", True)])
        field = attrs["field"]
        fieldType = attrs["field_type"]

        dbFieldType = self.aLayer.GetFieldType(field)

        if fieldType != dbFieldType:
            raise ValueError(_("xml field type differs from database!"))

        # setup conversion routines depending on the kind of data
        # we will be seeing later on
        if fieldType == FIELDTYPE_STRING:
            self.conv = str
        elif fieldType == FIELDTYPE_INT:
            self.conv = lambda p: int(float(p))
        elif fieldType == FIELDTYPE_DOUBLE:
            self.conv = float

        self.aLayer.SetClassificationColumn(field)

    def end_classification(self, name, qname): 
        pass

    def start_clnull(self, name, qname, attrs):
        self.cl_group = ClassGroupDefault()
        self.cl_group.SetLabel(self.encode(attrs.get((None, 'label'), "")))
        self.cl_prop = ClassGroupProperties()

    def end_clnull(self, name, qname):
        self.cl_group.SetProperties(self.cl_prop)
        self.aLayer.GetClassification().SetDefaultGroup(self.cl_group)
        del self.cl_group, self.cl_prop

    def start_clpoint(self, name, qname, attrs):
        attrib_value = attrs.get((None, 'value'), "0")

        field = self.aLayer.GetClassificationColumn()
        if self.aLayer.GetFieldType(field) == FIELDTYPE_STRING:
            value = self.encode(attrib_value)
        else:
            value = self.conv(attrib_value)
        self.cl_group = ClassGroupSingleton(value)
        self.cl_group.SetLabel(self.encode(attrs.get((None, 'label'), "")))
        self.cl_prop = ClassGroupProperties()


    def end_clpoint(self, name, qname):
        self.cl_group.SetProperties(self.cl_prop)
        self.aLayer.GetClassification().AppendGroup(self.cl_group)
        del self.cl_group, self.cl_prop

    def start_clrange(self, name, qname, attrs):

        range = attrs.get((None, 'range'), None)
        # for backward compatibility (min/max are not saved)
        min   = attrs.get((None, 'min'), None)
        max   = attrs.get((None, 'max'), None)

        try:
            if range is not None:
                self.cl_group = ClassGroupRange(Range(range))
            elif min is not None and max is not None:
                self.cl_group = ClassGroupRange((self.conv(min), 
                                                 self.conv(max)))
            else:
                self.cl_group = ClassGroupRange(Range(None))

        except ValueError:
            raise ValueError(_("Classification range is not a number!"))

        self.cl_group.SetLabel(attrs.get((None, 'label'), ""))
        self.cl_prop = ClassGroupProperties()


    def end_clrange(self, name, qname):
        self.cl_group.SetProperties(self.cl_prop)
        self.aLayer.GetClassification().AppendGroup(self.cl_group)
        del self.cl_group, self.cl_prop

    def start_cldata(self, name, qname, attrs):
        self.cl_prop.SetLineColor(
            parse_color(attrs.get((None, 'stroke'), "None")))
        self.cl_prop.SetLineWidth(
            int(attrs.get((None, 'stroke_width'), "0")))
        self.cl_prop.SetFill(parse_color(attrs.get((None, 'fill'), "None")))

    def end_cldata(self, name, qname):
        pass

    def start_labellayer(self, name, qname, attrs):
        self.aLayer = self.aMap.LabelLayer()

    def start_label(self, name, qname, attrs):
        x = float(attrs[(None, 'x')])
        y = float(attrs[(None, 'y')])
        text = self.encode(attrs[(None, 'text')])
        halign = attrs[(None, 'halign')]
        valign = attrs[(None, 'valign')]
        self.aLayer.AddLabel(x, y, text, halign = halign, valign = valign)

    def characters(self, chars):
        pass


def load_session(filename, db_connection_callback = None):
    """Load a Thuban session from the file object file

    The db_connection_callback, if given should be a callable object
    that can be called like this:
       db_connection_callback(params, message)

    where params is a dictionary containing the known connection
    parameters and message is a string with a message why the connection
    failed. db_connection_callback should return a new dictionary with
    corrected and perhaps additional parameters like a password or None
    to indicate that the user cancelled.
    """
    handler = SessionLoader(db_connection_callback)
    handler.read(filename)

    session = handler.theSession
    # Newly loaded session aren't modified
    session.UnsetModified()

    handler.Destroy()

    return session

