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

__version__ = "$Revision: 1.7 $"

from Thuban import _
from Thuban.Model.scalebar import deriveInterval, roundInterval
from Thuban.Model.proj import PROJ_UNITS_METERS

from wxPython.wx import *

class ScaleBar:

    def __init__(self, map):
        self.map = map

    def DrawScaleBar(self, scale, dc, position, size):
        """Draw a scalebar on a given DC"""

        # Only draw a legend if the corresponding map has a layer
        if self.map is not None \
            and self.map.projection is not None \
            and len(self.map.layers) > 0 \
            and scale > 0.0:

            # We have a projection, draw the scalebar in bw
            BlackPen = wxBLACK_PEN
            BlackBrush = wxBLACK_BRUSH
            BlackText = wxBLACK
                
            # Get the dimension
            width, height = size
            posx, posy    = position
            l1width, l1height = dc.GetTextExtent("%d"%0)

            # Make a first guess for the interval (to get the size we have 
            # to reserve for the labels)
            interval, unit = deriveInterval(width, scale)
            l2width, l2height = dc.GetTextExtent("%d %s"%(interval,unit))
            width = width - 4.0 - l1width/2.0 -l2width/2.0
        
            # Having precised the width now the final interval can be calculated
            interval, unit  = deriveInterval(width, scale)
            interval, label = roundInterval(interval)
             
            if interval > 0.0:
                # We draw 2 rectangles with half the width
                if unit == 'km':
                    width = int(interval*1000.0*scale/2)
                else:
                    width = int(interval*scale/2)
            
                dc.SetPen(BlackPen)

                brush = wxBrush(wxWHITE, wxSOLID)
                dc.SetBrush(brush)
                dc.DrawRectangle(posx+4,posy+2,width,8)

                dc.SetBrush(BlackBrush)
                dc.DrawRectangle(posx+width+4,posy+2,width,8)

                dc.SetTextForeground(BlackText)
                dc.DrawText("%d"%0, posx+ 4 - l1width/2, posy+12)

                l2width, l2height = dc.GetTextExtent("%s %s"%(label, unit))
                dc.DrawText("%s %s"%(interval, unit), posx+ 2*width+4 - l2width/2, posy + 12)

