# Copyright (c) 2002, 2003 by Intevation GmbH
# Authors:
# Bernhard Herzog <bh@intevation.de>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with Thuban for details.

"""
Test the Map class
"""

__version__ = "$Revision: 2575 $"
# $Source$
# $Id: test_map.py 2575 2005-02-22 11:09:32Z jan $

import os
import unittest

import support
support.initthuban()

from Thuban.Model.messages import CHANGED, MAP_PROJECTION_CHANGED, \
     MAP_LAYERS_CHANGED, MAP_LAYERS_ADDED, MAP_LAYERS_REMOVED,\
     MAP_STACKING_CHANGED, LAYER_VISIBILITY_CHANGED, LAYER_LEGEND_CHANGED, \
     LAYER_CHANGED

from Thuban.Model.session import Session
from Thuban.Model.map import Map
from Thuban.Model.layer import Layer
from Thuban.Model.proj import Projection
from Thuban.Model.color import Color


class TestMapSimple(unittest.TestCase):

    """Very simple test cases for Map"""

    def test_initial_state(self):
        """Test Map's initial state"""
        map = Map("Test Map")
        self.assertEquals(map.Title(), "Test Map")
        self.assertEquals(map.Layers(), [])
        label_layer = map.LabelLayer()
        self.assertEquals(label_layer.Title(), "Labels")
        self.assertEquals(label_layer.Labels(), [])
        self.failIf(map.WasModified())
        map.Destroy()

    def test_empty_map(self):
        """Test empty Map"""
        map = Map("Test Map")
        self.assertEquals(map.BoundingBox(), None)
        self.assertEquals(map.ProjectedBoundingBox(), None)
        self.failIf(map.HasLayers())
        map.Destroy()


class TestMapBase(unittest.TestCase, support.SubscriberMixin):

    """Base class for Map test cases that test messages"""

    def setUp(self):
        """
        Clear the message list, create self.map and subscribe to its messages
        """
        self.clear_messages()

        # Create a Map and subscribe to all interesting channels.
        self.map = Map("Test Map")
        for channel in (CHANGED, 
                        MAP_PROJECTION_CHANGED, 
                        MAP_LAYERS_CHANGED,
                        MAP_LAYERS_ADDED,
                        MAP_LAYERS_REMOVED,
                        MAP_STACKING_CHANGED,
                        LAYER_VISIBILITY_CHANGED, 
                        LAYER_LEGEND_CHANGED,
                        LAYER_CHANGED):
            self.map.Subscribe(channel, self.subscribe_with_params, channel)

    def tearDown(self):
        """Destroy self.map and self.session and clear the message list"""
        if hasattr(self, "session"):
            self.session.Destroy()
            self.session = None
        self.map.Destroy()
        self.map = None
        self.clear_messages()


class TestMapAddLayer(TestMapBase):

    """Simple test cases involving messages"""

    def test_add_layer(self):
        """Test Map.AddLayer"""
        # make sure the created Map is unmodified
        session = self.session = Session("Test session for %s" %self.__class__)
        self.failIf(self.map.WasModified())
        self.failIf(self.map.HasLayers())

        # add a layer and check the result
        filename = os.path.join("..", "Data", "iceland", "roads-line.shp")
        roads = Layer("Roads", session.OpenShapefile(filename))
        self.map.AddLayer(roads)
        self.assertEquals(self.map.Layers(), [roads])
        self.check_messages([(self.map, MAP_LAYERS_CHANGED),
                             (self.map, MAP_LAYERS_ADDED)])
        self.assert_(self.map.WasModified())
        self.assert_(self.map.HasLayers())


class TestMapWithContents(TestMapBase, support.FloatComparisonMixin):

    """More complex Map test cases with messages that.

    All test cases here start with a non-empty map.
    """

    def setUp(self):
        """Extend the inherited method to also fill the Map.

        Put some layers into the map created by the inherited method and
        reset its modified flag. Make also sure that the list of
        received messages is empty.
        """
        TestMapBase.setUp(self)
        self.session = Session("Test session for %s" % self.__class__)
        open_shp = self.session.OpenShapefile
        self.arc_layer = Layer("Roads",
                               open_shp(os.path.join("..", "Data", "iceland",
                                                     "roads-line.shp")))
        self.poly_layer = Layer("Political",
                                open_shp(os.path.join("..", "Data", "iceland",
                                                      "political.shp")))
        self.map.AddLayer(self.arc_layer)
        self.map.AddLayer(self.poly_layer)
        self.map.UnsetModified()
        self.clear_messages()

    def tearDown(self):
        TestMapBase.tearDown(self)
        self.session = None
        self.map = None
        self.poly_layer = self.arc_layer = None

    def test_remove_layer(self):
        """Test Map.RemoveLayer"""
        self.map.RemoveLayer(self.arc_layer)
        self.assert_(self.map.WasModified())
        self.assertEquals(self.map.Layers(), [self.poly_layer])
        self.map.UnsetModified()
        self.check_messages([(self.map, MAP_LAYERS_CHANGED),
                             (self.map, MAP_LAYERS_REMOVED),
                             (CHANGED,)])

    def test_clear_layers(self):
        """Test Map.ClearLayers"""
        self.map.ClearLayers()
        self.assertEquals(self.map.Layers(), [])
        self.assertEquals(self.map.LabelLayer().Labels(), [])
        self.check_messages([(MAP_LAYERS_CHANGED,),
                             (self.map, MAP_LAYERS_CHANGED),
                             (self.map, MAP_LAYERS_REMOVED)])
        self.assert_(self.map.WasModified())
        self.failIf(self.map.HasLayers())

    def test_raise_layer(self):
        """Test Map.RaiseLayer"""
        self.map.RaiseLayer(self.arc_layer)
        self.assertEquals(self.map.Layers(), [self.poly_layer, self.arc_layer])
        self.check_messages([(self.map, MAP_LAYERS_CHANGED),
                             (self.map, MAP_STACKING_CHANGED)])
        self.assert_(self.map.WasModified())

    def test_raise_layer_top(self):
        """Test Map.MoveLayerToTop"""
        open_shp = self.session.OpenShapefile
        dummy = Layer("Roads",
                      open_shp(os.path.join("..", "Data", "iceland",
                                            "roads-line.shp")))
        self.map.AddLayer(dummy)
        self.clear_messages()

        self.map.MoveLayerToTop(self.poly_layer)
        self.assertEquals(self.map.Layers(), 
                          [self.arc_layer, dummy, self.poly_layer])
        self.check_messages([(self.map, MAP_LAYERS_CHANGED),
                             (self.map, MAP_STACKING_CHANGED)])
        self.assert_(self.map.WasModified())

        self.map.RemoveLayer(dummy)

    def test_lower_layer_bottom(self):
        """Test Map.MoveLayerToBottom"""
        open_shp = self.session.OpenShapefile
        dummy = Layer("Roads",
                      open_shp(os.path.join("..", "Data", "iceland",
                                            "roads-line.shp")))
        self.map.AddLayer(dummy)
        self.clear_messages()

        self.map.MoveLayerToBottom(dummy)
        self.assertEquals(self.map.Layers(), 
                          [dummy, self.arc_layer, self.poly_layer])
        self.check_messages([(self.map, MAP_LAYERS_CHANGED),
                             (self.map, MAP_STACKING_CHANGED)])
        self.assert_(self.map.WasModified())

        self.map.RemoveLayer(dummy)

    def test_raise_highest_layer(self):
        """Test Map.RaiseLayer with highest layer

        Attempting to raise the highest layer should not modify the map.
        In particular it should not send any messages.
        """
        self.map.RaiseLayer(self.poly_layer)
        self.assertEquals(self.map.Layers(), [self.arc_layer, self.poly_layer])
        self.check_messages([])
        self.failIf(self.map.WasModified())

    def test_lower_layer(self):
        """Test Map.LowerLayer"""
        self.map.LowerLayer(self.poly_layer)
        self.assertEquals(self.map.Layers(), [self.poly_layer, self.arc_layer])
        self.check_messages([(self.map, MAP_LAYERS_CHANGED),
                             (self.map, MAP_STACKING_CHANGED)])
        self.assert_(self.map.WasModified())

    def test_lower_lowest_layer(self):
        """Test Map.LowerLayer with lowest layer.

        Attempting to lower the lowest layer should not modify the map.
        In particular it should not send any messages.
        """
        self.map.LowerLayer(self.arc_layer)
        self.assertEquals(self.map.Layers(), [self.arc_layer, self.poly_layer])
        self.check_messages([])
        self.failIf(self.map.WasModified())

    def test_bounding_box(self):
        """Test Map.BoundingBox"""
        self.assertFloatSeqEqual(self.map.BoundingBox(),
                                 (-24.546524047851562, 63.286754608154297,
                                  -13.495815277099609, 66.563774108886719))

    def test_projected_bounding_box(self):
        """Test Map.ProjectedBoundingBox"""
        proj = Projection(["zone=26", "proj=utm", "ellps=clrk66"])
        self.map.SetProjection(proj)
        self.assertFloatSeqEqual(self.map.ProjectedBoundingBox(),
                                 (608873.03380603762, 7019694.6517963577,
                                  1173560.0288053728, 7447353.2203218574),
                                 epsilon = 1e-5)

    def test_set_projection(self):
        """Test Map.SetProjection"""
        proj = Projection(["zone=26", "proj=utm", "ellps=clrk66"])
        self.map.SetProjection(proj)
        self.check_messages([(self.map, None, MAP_PROJECTION_CHANGED)])
        self.assert_(self.map.WasModified())

    def test_tree_info(self):
        """Test Map.TreeInfo"""
        proj = Projection(["zone=26", "proj=utm", "ellps=clrk66"])
        self.map.SetProjection(proj)
        # compute the extent string because there are platform
        # differences in the way %g is handled:
        # glibc: "%g" % 7.01969e+06 == "7.01969e+06"
        # w32/VC: "%g" % 7.01969e+06 == "7.01969e+006"
        extent = 'Extent (projected): (%g, %g, %g, %g)'\
                 % (608873, 7.01969e+06, 1.17356e+06, 7.44735e+06)
        self.assertEquals(self.map.TreeInfo(),
                          ('Map: Test Map',
                           [('Extent (lat-lon):'
                             ' (-24.5465, 63.2868, -13.4958, 66.5638)'),
                            extent,
                            ('Projection',
                             ['zone=26', 'proj=utm', 'ellps=clrk66']),
                            self.poly_layer,
                            self.arc_layer,
                            self.map.LabelLayer()]))

    def test_forwarding_visibility(self):
        """Test Map's forwarding of Layer.SetVisible messages"""
        self.poly_layer.SetVisible(0)
        self.check_messages([(self.poly_layer, LAYER_VISIBILITY_CHANGED)])

    def test_unset_modified(self):
        """Test Map.UnsetModified.

        Test whether a change to a layer results in the map being
        considered modified and test whether then calling the map's
        UnsetModified clears the changed flag in the layer as well.
        """
        self.failIf(self.map.WasModified())
        self.poly_layer.GetClassification().SetDefaultFill(Color(0.0, 0.5, 1.0))
        self.assert_(self.map.WasModified())
        self.map.UnsetModified()
        self.failIf(self.map.WasModified())
        self.failIf(self.poly_layer.WasModified())
        self.check_messages([(self.poly_layer, LAYER_CHANGED),
                             (CHANGED,)])

if __name__ == "__main__":
    support.run_tests()

