# -*- coding:iso-8859-15 -*-
# Copyright (C) 2004 by Intevation GmbH
# Authors:
# Jan Schüngel <jschuengel@intevation.de>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with Thuban for details.

"""
This modul extend Thuban with the possibility to handle
UMN MapServer mapfiles.
"""

__version__ = "$Revision: 2858 $"
# $Source$
# $Id: mf_handle.py 2858 2008-07-29 06:17:34Z elachuni $


# ###################################
#
# import necessary modules
#
# ###################################

import os, sys

# mapscript
from mapscript import mapObj, layerObj

# wxPython support
# TODO: explicitly use from .. import
import wx
from wx import grid

# Thuban
# use _() already now for all strings that may later be translated
from Thuban import _

# Thuban has named commands which can be registered in the central
# instance registry.
from Thuban.UI.command import registry, Command

# needed to add the new menu
from Thuban.UI.mainwindow import main_menu

# import Map Object for the Mapfile
from mapfile import MF_Map

from Thuban.UI.colordialog import ColorDialog

from mapfile import unit_type, legend_status_type, legend_position_type, \
                    label_font_type, scalebar_status_type, scalebar_style_type, \
                    scalebar_position_type, label_position_type

# ###################################
#
# Mainpart of the Extension
#
# ###################################

ID_COLOR_CHANGE= 8001
ID_IMGCOLOR_CHANGE = 8002

class Map_Dialog(wx.Dialog):
    
    def __init__(self, parent, ID, title,
                 pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=wx.DEFAULT_DIALOG_STYLE):
                     
        # initialize the Dialog
        wx.Dialog.__init__(self, parent, ID, title, pos, size, style)

        # parent.canvas.Map()
        self.tb_map = parent.canvas.Map()
        self.tb_map_umn = self.tb_map.extension_umn_mapobj

        # create name
        box_name = wx.BoxSizer(wx.HORIZONTAL)
        box_name.Add(wx.StaticText(self, -1, _("Map-Name:")), 0,
                     wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)
        box_name.Add(wx.StaticText(self, -1, self.tb_map.Title()), 0,
                     wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)  

        #create size settings
        insidetxt = self.tb_map_umn.get_size()
        staticSize = wx.StaticBox(self, 1010, _("Size"), style = 0, 
	                         name = "staticBox",   )
        box_size = wx.StaticBoxSizer(staticSize, wx.VERTICAL)
        
        box_sizepartWidth = wx.BoxSizer(wx.HORIZONTAL)
        box_sizepartWidth.Add(wx.StaticText(self, -1, _("Width: ")), 0, wx.ALL, 4)
        self.text_width = wx.TextCtrl(self, -1, str(insidetxt[0]))
        box_sizepartWidth.Add(self.text_width, 2, wx.ALL, 4)
        box_size.Add(box_sizepartWidth, 0, wx.ALIGN_RIGHT | wx.ALL, 5)
        box_sizepartHeight = wx.BoxSizer(wx.HORIZONTAL)
        box_sizepartHeight.Add(wx.StaticText(self, -1, _("Height: ")), 0,
	                                    wx.ALL, 4)
        self.text_height = wx.TextCtrl(self, -1, str(insidetxt[1]))
        box_sizepartHeight.Add(self.text_height, 2, wx.ALL, 4)
        box_size.Add(box_sizepartHeight, 0, wx.ALIGN_RIGHT | wx.ALL, 5)
        
        #  get the web object
        self.tb_map = parent.canvas.Map()
        self.tb_map_umn = self.tb_map.extension_umn_mapobj
        
        #get the imagetype
        umn_imagetype = self.tb_map_umn.get_imagetype()
        # create a list with the outputformat names
        umn_outputformats = []
        for format in self.tb_map_umn.get_alloutputformats():
            umn_outputformats.append(format.get_name())
        #Imagetype selector
        box_imagetypeStatic = wx.StaticBox(self, -1, _("Image Type"),
                                          style = 0, name = "imagetype")
        box_imagetype = wx.StaticBoxSizer(box_imagetypeStatic, wx.VERTICAL)
        self.choice_imgtype = wx.Choice(self, 8060, (80, 50), 
                                        choices = umn_outputformats)
        wx.EVT_CHOICE(self, 8060, self.EvtChoiceBox)
        self.choice_imgtype.SetStringSelection(umn_imagetype)
        box_imagetype.Add(self.choice_imgtype,0, wx.EXPAND, wx.ALL, 5)    
        
        #unittype
        insideunit = self.tb_map_umn.get_units()
        #Unittype selector
        box_unitsStatic = wx.StaticBox(self, 1011, _("Unit Type"),
	                              style = 0, name = "imagecolor")
        box_units = wx.StaticBoxSizer(box_unitsStatic, wx.VERTICAL)
        sam = []
        for key in unit_type:
            sam.append(unit_type[key])
        self.choice_units = wx.Choice(self, 40, (80, 50), choices = sam)
        self.choice_units.SetStringSelection(insideunit)
        box_units.Add(self.choice_units,0, wx.EXPAND, wx.ALL, 5)        
    
        # color chouser
        box_colorStatic = wx.StaticBox(self, 1011, _("ImageColor"),
	                              style = 0, name = "imagecolor")
        box_color = wx.StaticBoxSizer(box_colorStatic, wx.VERTICAL)
        
        # preview box
        self.previewcolor = wx.Panel(self,99, name = 'backgroundPanel',
	                            style = wx.SIMPLE_BORDER | wx.CLIP_CHILDREN)
        imagecolor = self.tb_map_umn.get_imagecolor()
        self.previewcolor.SetBackgroundColour(wx.Colour(imagecolor.get_red(),
        imagecolor.get_green(), imagecolor.get_blue()))
        box_color.Add(self.previewcolor, 1, wx.GROW | wx.ALL, 5)
        # color change button, opens a new color dialog
        button = wx.Button(self, ID_COLOR_CHANGE, _("Change Color"))
        button.SetFocus()
        wx.EVT_BUTTON(self, ID_COLOR_CHANGE, self.OnChangeColor)
        box_color.Add(button, 1, wx.EXPAND|wx.ALL, 5)
        
        # status
        umn_status = self.tb_map_umn.get_status()
        self.choice_status = wx.RadioBox(self, -1, choices=["True","False"],
              label='status', majorDimension=1,
              name='status check', size=wx.DefaultSize, style=wx.RA_SPECIFY_ROWS)
        self.choice_status.SetStringSelection(str(umn_status))
        
        #buttons
        box_buttons = wx.BoxSizer(wx.HORIZONTAL)
        button = wx.Button(self, wx.ID_OK, _("OK"))
        box_buttons.Add(button, 0, wx.ALL, 5)
        button = wx.Button(self, wx.ID_CANCEL, _("Cancel"))
        box_buttons.Add(button, 0, wx.ALL, 5)
        #button functions
        wx.EVT_BUTTON(self, wx.ID_OK, self.OnOK)
        wx.EVT_BUTTON(self, wx.ID_CANCEL, self.OnCancel)
        
        #add all boxes to the box top
        top = wx.BoxSizer(wx.VERTICAL)
        top.Add(box_name, 0, wx.EXPAND |wx.ALL, 5)
        top.Add(box_size, 0, wx.EXPAND |wx.ALL, 5)
        top.Add(box_imagetype,0, wx.EXPAND |wx.ALL, 5)
        top.Add(box_units,0, wx.EXPAND |wx.ALL, 5)
        top.Add(box_color,0, wx.EXPAND |wx.ALL, 5)     
        top.Add(self.choice_status,0, wx.EXPAND |wx.ALL, 5)   
        top.Add(box_buttons, 0, wx.ALIGN_RIGHT)
        
        # final layout settings
        self.SetSizer(top)
        top.Fit(self)

    def OnChangeColor(self, event):
        cur = self.tb_map_umn.get_imagecolor().get_thubancolor()
        dialog = ColorDialog(self)
        dialog.SetColor(cur)
        self.retcolor = None
        if dialog.ShowModal() == wx.ID_OK:
            self.retcolor = dialog.GetColor()
        dialog.Destroy()
        if self.retcolor:
            self.redcolor = int(round(self.retcolor.red*255))
            self.greencolor = int(round(self.retcolor.green*255))
            self.bluecolor = int(round(self.retcolor.blue*255))
            self.previewcolor.SetBackgroundColour(wx.Colour((self.redcolor), 
                                            int(self.greencolor), int(self.bluecolor)))
            # refresh the colorbox to show the new color
            self.previewcolor.Refresh()
    
    def EvtChoiceBox(self, event):
        outformat = self.tb_map_umn.get_outputformat().get_name()

    def RunDialog(self):
        self.ShowModal()
        self.Destroy()

    def end_dialog(self, result):
        self.result = result
        if self.result is not None:
            self.EndModal(wx.ID_OK)
        else:
            self.EndModal(wx.ID_CANCEL)
        self.Show(False)

    def OnOK(self, event):
        try:
            width = int(self.text_width.GetValue())
            height = int(self.text_height.GetValue())
        except ValueError, e:
            dlg = wx.MessageDialog (self, "Width / Height: " + str(e),
                                    "Warning", wx.OK)
            dlg.ShowModal()
            return
        self.tb_map_umn.set_size(width, height)
        self.tb_map_umn.set_units(self.choice_units.GetStringSelection())
        if self.choice_status.GetStringSelection() == "True":
            self.tb_map_umn.set_status(True)
        else:
            self.tb_map_umn.set_status(False)
        previewcolor = self.previewcolor.GetBackgroundColour()
        self.tb_map_umn.get_imagecolor().set_rgbcolor(previewcolor.Red(),
                    previewcolor.Green(), previewcolor.Blue())
        self.tb_map_umn.set_imagetype(self.choice_imgtype.GetStringSelection())
        self.result ="OK"
        self.end_dialog(self.result)

    def OnCancel(self, event):
        self.end_dialog(None)


class Web_Dialog(wx.Dialog):
        
    def __init__(self, parent, ID, title,
                 pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=wx.DEFAULT_DIALOG_STYLE):
                     
        # initialize the Dialog
        wx.Dialog.__init__(self, parent, ID, title, pos, size, style)

        #  get the web object
        self.tb_map = parent.canvas.Map()
        self.umn_web = self.tb_map.extension_umn_mapobj.get_web()
    
        # Template 
        box_template = wx.BoxSizer(wx.HORIZONTAL)
        box_template.Add(wx.StaticText(self, -1, _("Template:")), 0,
                     wx.ALL|wx.ALIGN_LEFT, 4)
        self.text_template = wx.TextCtrl(self, -1, 
                                    str(self.umn_web.get_template()))
        self.text_template.SetSize((250,self.text_template.GetSize()[1]))
        box_template.Add(self.text_template, 0,
                     wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)  
    
        # Imagepath 
        box_imagepath = wx.BoxSizer(wx.HORIZONTAL)
        box_imagepath.Add(wx.StaticText(self, -1, _("Imagepath:")), 0,
                     wx.ALL|wx.ALIGN_LEFT, 4)
        self.text_imagepath = wx.TextCtrl(self, -1, 
	                                 str(self.umn_web.get_imagepath()))
        box_imagepath.Add(self.text_imagepath, 0,
                     wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)  

        # Imageurl 
        box_imageurl = wx.BoxSizer(wx.HORIZONTAL)
        box_imageurl.Add(wx.StaticText(self, -1, _("Imageurl:")), 0,
                     wx.ALL|wx.ALIGN_LEFT, 4)
        self.text_imageurl = wx.TextCtrl(self, -1, 
                                    str(self.umn_web.get_imageurl()))
        box_imageurl.Add(self.text_imageurl, 0,
                     wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)  
        
        #buttons
        box_buttons = wx.BoxSizer(wx.HORIZONTAL)
        button = wx.Button(self, wx.ID_OK, _("OK"))
        box_buttons.Add(button, 0, wx.ALL, 5)
        button = wx.Button(self, wx.ID_CANCEL, _("Cancel"))
        box_buttons.Add(button, 0, wx.ALL, 5)
        #set the button funcitons
        wx.EVT_BUTTON(self, wx.ID_OK, self.OnOK)
        wx.EVT_BUTTON(self, wx.ID_CANCEL, self.OnCancel)      
      
        # compose the final dialog
        top = wx.BoxSizer(wx.VERTICAL)
        top.Add(box_template, 0, wx.EXPAND |wx.ALL, 5)
        top.Add(box_imagepath, 0, wx.EXPAND |wx.ALL, 5)
        top.Add(box_imageurl, 0, wx.EXPAND |wx.ALL, 5)
        top.Add(box_buttons, 0, wx.ALIGN_RIGHT)
        
        # final layout settings
        self.SetSizer(top)
        top.Fit(self)

    def RunDialog(self):
        self.ShowModal()
        self.Destroy()

    def end_dialog(self, result):
        self.result = result
        if self.result is not None:
            self.EndModal(wx.ID_OK)
        else:
            self.EndModal(wx.ID_CANCEL)
        self.Show(False)

    def OnOK(self, event):
        self.umn_web.set_template(self.text_template.GetValue())
        self.umn_web.set_imagepath(self.text_imagepath.GetValue())
        self.umn_web.set_imageurl(self.text_imageurl.GetValue())
        self.result ="OK"
        self.end_dialog(self.result)

    def OnCancel(self, event):
        self.end_dialog(None)

ID_METADATA_CHANGE = 8020

from Extensions.umn_mapserver.mapfile import MF_Layer

class Layer_Dialog(wx.Dialog):
        
    def __init__(self, parent, ID, title,
                 pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=wx.DEFAULT_DIALOG_STYLE):
                     
        # initialize the Dialog
        wx.Dialog.__init__(self, parent, ID, title, pos, size, style)

        #  get the web object
        self.tb_layer = parent.current_layer()
        if hasattr(self.tb_layer,"extension_umn_layerobj"):
            self.umn_layer = self.tb_layer.extension_umn_layerobj
        else:
            newlayerobj = parent.canvas.Map().extension_umn_mapobj.create_new_layer()
            self.tb_layer.extension_umn_layerobj = newlayerobj
            self.umn_layer = self.tb_layer.extension_umn_layerobj
        
        # create name
        layer_name = wx.BoxSizer(wx.HORIZONTAL)
        layer_name.Add(wx.StaticText(self, -1, _("Layer-Name:")), 0,
                     wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)
        layer_name.Add(wx.StaticText(self, -1, self.tb_layer.Title()), 0,
                     wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)  
 
        # metadata button
        metadata_button = wx.Button(self, ID_METADATA_CHANGE, _("Edit Metadata"))
        wx.EVT_BUTTON(self, ID_METADATA_CHANGE, self.OnChangeMetadata)
        
        # Group 
        box_group = wx.BoxSizer(wx.HORIZONTAL)
        if self.umn_layer.get_group():
            umn_layer_group = self.umn_layer.get_group()
        else:
            umn_layer_group = ""
        box_group.Add(wx.StaticText(self, -1, _("Group:")), 0,
                     wx.ALL|wx.ALIGN_LEFT, 4)
        self.text_group = wx.TextCtrl(self, -1, 
                                    str(umn_layer_group))
        self.text_group.SetSize((250,self.text_group.GetSize()[1]))
        box_group.Add(self.text_group, 0,
                     wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)  
        
        # buttons
        box_buttons = wx.BoxSizer(wx.HORIZONTAL)
        button = wx.Button(self, wx.ID_OK, _("OK"))
        box_buttons.Add(button, 0, wx.ALL, 5)
        button = wx.Button(self, wx.ID_CANCEL, _("Cancel"))
        box_buttons.Add(button, 0, wx.ALL, 5)
        #set the button funcitons
        wx.EVT_BUTTON(self, wx.ID_OK, self.OnOK)
        wx.EVT_BUTTON(self, wx.ID_CANCEL, self.OnCancel)      
      
        # compose the final dialog
        top = wx.BoxSizer(wx.VERTICAL)
        #top.Add(box_template, 0, wx.EXPAND |wx.ALL, 5)
        top.Add(layer_name, 0, wx.EXPAND|wx.ALL, 5)
        top.Add(box_group, 0, wx.EXPAND|wx.ALL, 5)
        top.Add(metadata_button, 0, wx.EXPAND|wx.ALL, 5)
        top.Add(box_buttons, 0, wx.ALIGN_RIGHT)
        
        # final layout settings
        self.SetSizer(top)
        top.Fit(self)

    def OnChangeMetadata(self, event):
        # set the umn_label for scalebar so the Label_Dialog can be used
        self.umn_metadata= self.umn_layer.get_metadata()
        dialog = Metadata_Dialog(self, -1, "Layer Metadata Settings",
	                      size=wx.Size(450, 200),
                 style = wx.DEFAULT_DIALOG_STYLE
                 )
        dialog.CenterOnScreen()
        if dialog.ShowModal() == wx.ID_OK:
            return
        dialog.Destroy()
        
    
    def RunDialog(self):
        self.ShowModal()
        self.Destroy()

    def end_dialog(self, result):
        self.result = result
        if self.result is not None:
            self.EndModal(wx.ID_OK)
        else:
            self.EndModal(wx.ID_CANCEL)
        self.Show(False)

    def OnOK(self, event):
        if self.text_group.GetValue() == "":
            self.umn_layer.set_group(None)
        else:
            self.umn_layer.set_group(self.text_group.GetValue())
        self.result ="OK"
        self.end_dialog(self.result)

    def OnCancel(self, event):
        self.end_dialog(None)


ID_LABEL_CHANGE = 8011

class Legend_Dialog(wx.Dialog):
        
    def __init__(self, parent, ID, title,
                 pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=wx.DEFAULT_DIALOG_STYLE):
                     
        # initialize the Dialog
        wx.Dialog.__init__(self, parent, ID, title, pos, size, style)

        #  get the web object
        self.tb_map = parent.canvas.Map()
        self.umn_legend = self.tb_map.extension_umn_mapobj.get_legend()

        # create the Keysize
        keySize = wx.StaticBox(self, 1010, _("KeySize"), style = 0,
	                      name = "KeySize Box",   )
        box_keysize = wx.StaticBoxSizer(keySize, wx.VERTICAL)
        umn_legend_keysize = self.umn_legend.get_keysize()
        box_sizepartWidth = wx.BoxSizer(wx.HORIZONTAL)        
        box_sizepartWidth.Add(wx.StaticText(self, -1, _("Width: ")), 0, wx.ALL, 2)
        self.text_keysize_width = wx.SpinCtrl(self, -1, 
                              value=str(umn_legend_keysize[0]), max=100, min=0,
                              name='keywidth', style=wx.SP_ARROW_KEYS)
        box_sizepartWidth.Add(self.text_keysize_width, 2, wx.ALL, 2)
        box_keysize.Add(box_sizepartWidth, 0, wx.ALIGN_RIGHT | wx.ALL, 2)
        box_sizepartHeight = wx.BoxSizer(wx.HORIZONTAL)
        box_sizepartHeight.Add(wx.StaticText(self, -1, _("Height: ")), 0, wx.ALL, 2),
        self.text_keysize_height = wx.SpinCtrl(self, -1, 
                              value=str(umn_legend_keysize[1]), max=100, min=0,
                              name='keyheight', style=wx.SP_ARROW_KEYS)
        box_sizepartHeight.Add(self.text_keysize_height, 2, wx.ALL, 2)
        box_keysize.Add(box_sizepartHeight, 0, wx.ALIGN_RIGHT | wx.ALL, 2)
        
        # create the Keyspacing
        keySpacing= wx.StaticBox(self, 1010, _("KeySpacing"), style = 0,
	                        name = "KeySpacing Box",   )
        box_keyspacing = wx.StaticBoxSizer(keySpacing, wx.VERTICAL)
        umn_legend_keyspacing = self.umn_legend.get_keyspacing()
        box_sizepartWidth = wx.BoxSizer(wx.HORIZONTAL)        
        box_sizepartWidth.Add(wx.StaticText(self, -1, _("Width: ")), 0, wx.ALL, 2)
        self.text_keyspacing_width = wx.SpinCtrl(self, -1, 
                              value=str(umn_legend_keyspacing[0]), max=100,
			      min=0, name='spacingwidth', style=wx.SP_ARROW_KEYS)
        box_sizepartWidth.Add(self.text_keyspacing_width, 2, wx.ALL, 2)
        box_keyspacing.Add(box_sizepartWidth, 0, wx.ALIGN_RIGHT | wx.ALL, 2)
        box_sizepartHeight = wx.BoxSizer(wx.HORIZONTAL)
        box_sizepartHeight.Add(wx.StaticText(self, -1, _("Height: ")), 0, wx.ALL, 2),
        self.text_keyspacing_height = wx.SpinCtrl(self, -1, 
                              value=str(umn_legend_keyspacing[1]), max=100,
			      min=0,name='spacingheight', style=wx.SP_ARROW_KEYS)
        box_sizepartHeight.Add(self.text_keyspacing_height, 2, wx.ALL, 2)
        box_keyspacing.Add(box_sizepartHeight, 0, wx.ALIGN_RIGHT | wx.ALL, 2)

        # color chooser
        box_colorStatic = wx.StaticBox(self, 1011, _("ImageColor"),  style = 0,
	                              name = "imagecolor")
        box_color = wx.StaticBoxSizer(box_colorStatic, wx.VERTICAL)
        # preview box
        self.previewcolor = wx.Panel(self, 99, name = 'imagecolorPanel',
	                            style = wx.SIMPLE_BORDER | wx.CLIP_CHILDREN)
        imagecolor = self.umn_legend.get_imagecolor()
        self.previewcolor.SetBackgroundColour(wx.Colour(imagecolor.get_red(),
        imagecolor.get_green(), imagecolor.get_blue()))
        box_color.Add(self.previewcolor, 1, wx.GROW | wx.ALL, 5)
        # color change button, opens a new color dialog
        button = wx.Button(self, ID_COLOR_CHANGE, _("Change Color"))
        button.SetFocus()
        wx.EVT_BUTTON(self, ID_COLOR_CHANGE, self.OnChangeColor)
        box_color.Add(button, 1, wx.EXPAND|wx.ALL, 5)

        # status
        umn_legend_status= self.umn_legend.get_status(mode="string")
        possible_choices = []
        for key in legend_status_type:
            possible_choices.append(legend_status_type[key])
        self.choice_status = wx.RadioBox(self, -1, choices=possible_choices,
              label='Status', majorDimension=1,
              name='status check', size=wx.DefaultSize, style=wx.RA_SPECIFY_ROWS)
        self.choice_status.SetStringSelection(umn_legend_status)

        # create the positionbox
        umn_legend_position= self.umn_legend.get_position(mode="string")
        possible_choices = []
        for key in legend_position_type:
            possible_choices.append(legend_position_type[key])
        self.choice_position = wx.RadioBox(self, -1, choices=possible_choices,
                                          label='Position', majorDimension=1,
                                          name='position check', 
					  size=wx.DefaultSize,
					  style=wx.RA_SPECIFY_ROWS)
        self.choice_position.SetStringSelection(umn_legend_position)
        
        # button for label
        labelbutton = wx.Button(self, ID_LABEL_CHANGE, _("Change Label"))
        wx.EVT_BUTTON(self, ID_LABEL_CHANGE, self.OnChangeLabel)
        
        #buttons
        box_buttons = wx.BoxSizer(wx.HORIZONTAL)
        button = wx.Button(self, wx.ID_OK, _("OK"))
        box_buttons.Add(button, 0, wx.ALL, 5)
        button = wx.Button(self, wx.ID_CANCEL, _("Cancel"))
        box_buttons.Add(button, 0, wx.ALL, 5)
        #set the button funcitons
        wx.EVT_BUTTON(self, wx.ID_OK, self.OnOK)
        wx.EVT_BUTTON(self, wx.ID_CANCEL, self.OnCancel)        
        
        # compose the final layout
        top = wx.BoxSizer(wx.VERTICAL)
        top.Add(box_keysize,0, wx.EXPAND |wx.ALL, 5) 
        top.Add(box_keyspacing,0, wx.EXPAND |wx.ALL, 5) 
        top.Add(box_color,0, wx.EXPAND |wx.ALL, 5) 
        top.Add(self.choice_status,0, wx.EXPAND |wx.ALL, 5) 
        top.Add(self.choice_position,0, wx.EXPAND |wx.ALL, 5) 
        top.Add(labelbutton, 1, wx.EXPAND|wx.ALL, 5)
        top.Add(box_buttons, 0, wx.ALIGN_RIGHT)
        
        # final layout settings
        self.SetSizer(top)
        top.Fit(self)
    
    def OnChangeLabel(self, event):
        self.umn_label = self.umn_legend.get_label()
        dialog = Label_Dialog(self, -1, "Legend Label Settings",
	                      size=wx.Size(350, 200),
                 style = wx.DEFAULT_DIALOG_STYLE
                 )
        dialog.CenterOnScreen()
        if dialog.ShowModal() == wx.ID_OK:
            return
        dialog.Destroy()
    
    def OnChangeColor(self, event):
        cur = self.umn_legend.get_imagecolor().get_thubancolor()
        dialog = ColorDialog(self)
        dialog.SetColor(cur)
        self.retcolor = None
        if dialog.ShowModal() == wx.ID_OK:
            self.retcolor = dialog.GetColor()
        dialog.Destroy()
        if self.retcolor:
            self.redcolor = int(round(self.retcolor.red*255))
            self.greencolor = int(round(self.retcolor.green*255))
            self.bluecolor = int(round(self.retcolor.blue*255))
            self.previewcolor.SetBackgroundColour(wx.Colour(int(self.redcolor), 
                                                           int(self.greencolor),
					                   int(self.bluecolor)))
            # refresh the colorbox to show the new color
            self.previewcolor.Refresh()

    def RunDialog(self):
        self.ShowModal()
        self.Destroy()

    def end_dialog(self, result):
        self.result = result
        if self.result is not None:
            self.EndModal(wx.ID_OK)
        else:
            self.EndModal(wx.ID_CANCEL)
        self.Show(False)

    def OnOK(self, event):
        self.umn_legend.set_keysize(self.text_keysize_width.GetValue(),
                                    self.text_keysize_height.GetValue())
        self.umn_legend.set_keyspacing(self.text_keyspacing_width.GetValue(),
                                    self.text_keyspacing_height.GetValue())
        self.umn_legend.set_status(self.choice_status.GetStringSelection())
        self.umn_legend.set_position(self.choice_position.GetStringSelection())
        previewcolor = self.previewcolor.GetBackgroundColour()
        self.umn_legend.get_imagecolor().set_rgbcolor(previewcolor.Red(),
                    previewcolor.Green(), previewcolor.Blue())
        self.result ="OK"
        self.end_dialog(self.result)

    def OnCancel(self, event):
        self.end_dialog(None)

class Label_Dialog(wx.Dialog):
    
    def __init__(self, parent, ID, title,
                 pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=wx.DEFAULT_DIALOG_STYLE):
                     
        # initialize the Dialog
        wx.Dialog.__init__(self, parent, ID, title, pos, size, style)

        #  get the web object
        self.umn_label = parent.umn_label

        # size
        labelsize= wx.StaticBox(self, 1010, _("Size"), style = 0,
	                       name = "Size Box",   )
        box_labelsize = wx.StaticBoxSizer(labelsize, wx.VERTICAL)
        umn_label_size= self.umn_label.get_size()
        box_size = wx.BoxSizer(wx.HORIZONTAL)        
        self.text_labelsize = wx.SpinCtrl(self, -1, 
                              value=str(umn_label_size), max=10, min=0,
                              name='size', style=wx.SP_ARROW_KEYS)
        box_size.Add(self.text_labelsize, 2, wx.ALL, 2)
        box_labelsize.Add(box_size, 0, wx.ALIGN_RIGHT | wx.ALL, 2)

        # color chooser
        box_colorStatic = wx.StaticBox(self, 1011, _("Color"),  style = 0,
	                              name = "color")
        box_color = wx.StaticBoxSizer(box_colorStatic, wx.VERTICAL)
        # preview box
        self.previewcolor = wx.Panel(self, 99, name = 'colorPanel',
	                            style = wx.SIMPLE_BORDER | wx.CLIP_CHILDREN)
        color = self.umn_label.get_color()
        self.previewcolor.SetBackgroundColour(wx.Colour(color.get_red(),
        color.get_green(), color.get_blue()))
        box_color.Add(self.previewcolor, 1, wx.GROW | wx.ALL, 5)
        # color change button, opens a new color dialog
        button = wx.Button(self, ID_COLOR_CHANGE, _("Change Color"))
        button.SetFocus()
        wx.EVT_BUTTON(self, ID_COLOR_CHANGE, self.OnChangeColor)
        box_color.Add(button, 1, wx.EXPAND|wx.ALL, 5)

        #get the set type
        insidetype = self.umn_label.get_type()
        #create the type selector for fonttype (Bitmap, TrueType)
        # TODO: Truetype is not supported yet
        box_typeStatic = wx.StaticBox(self, 1011, _("Type"),  style = 0,
	                             name = "type")
        box_type = wx.StaticBoxSizer(box_typeStatic, wx.VERTICAL)
        sam = []
        for key in label_font_type:
            # dont add truetype
            #if key != 0:
            sam.append(label_font_type[key])
        self.choice_type = wx.Choice(self, 40, (80, 50), choices = sam)
        self.choice_type.SetStringSelection(insidetype)
        box_type.Add(self.choice_type,0, wx.EXPAND, wx.ALL, 5)        

        # Offset
        offset= wx.StaticBox(self, 1010, _("Offset"), style = 0,
	                    name = "Offset Box",   )
        box_offset = wx.StaticBoxSizer(offset, wx.VERTICAL)
        umn_label_offset = self.umn_label.get_offset()
        box_offsetX = wx.BoxSizer(wx.HORIZONTAL)        
        box_offsetX.Add(wx.StaticText(self, -1, _("X: ")), 0, wx.ALL, 2)
        self.text_offsetx = wx.SpinCtrl(self, -1, 
                              value=str(umn_label_offset[0]), max=20, min=0,
                              name='offsetX', style=wx.SP_ARROW_KEYS)
        box_offsetX.Add(self.text_offsetx, 2, wx.ALL, 2)
        box_offset.Add(box_offsetX, 0, wx.ALIGN_RIGHT | wx.ALL, 2)
        box_offsetY = wx.BoxSizer(wx.HORIZONTAL)
        box_offsetY.Add(wx.StaticText(self, -1, _("Y: ")), 0, wx.ALL, 2),
        self.text_offsety = wx.SpinCtrl(self, -1, 
                              value=str(umn_label_offset[1]), max=100, min=0,
                              name='offsetY', style=wx.SP_ARROW_KEYS)
        box_offsetY.Add(self.text_offsety, 2, wx.ALL, 2)
        box_offset.Add(box_offsetY, 0, wx.ALIGN_RIGHT | wx.ALL, 2)
        
        # partials
        umn_partials = self.umn_label.get_partials()
        self.choice_partials = wx.RadioBox(self, -1, choices=["True","False"],
                                          label='partials', majorDimension=1,
                                          name='partials check', 
					  size=wx.DefaultSize,
	                                  style=wx.RA_SPECIFY_ROWS)
        self.choice_partials.SetStringSelection(str(umn_partials))

        # force
        umn_force = self.umn_label.get_force()
        self.choice_force = wx.RadioBox(self, -1, choices=["True","False"],
              label='force', majorDimension=1,
              name='force check', size=wx.DefaultSize, style=wx.RA_SPECIFY_ROWS)
        self.choice_force.SetStringSelection(str(umn_force))

        # buffer
        buffer = wx.StaticBox(self, 1010, _("Buffer"), style = 0,
	                     name = "Buffer Box",   )
        box_buffer = wx.StaticBoxSizer(buffer, wx.VERTICAL)
        umn_buffer= self.umn_label.get_buffer()
        box_buffertext = wx.BoxSizer(wx.HORIZONTAL)        
        self.text_buffer = wx.SpinCtrl(self, -1, 
                              value=str(umn_buffer), max=10, min=0,
                              name='size', style=wx.SP_ARROW_KEYS)
        box_buffertext.Add(self.text_buffer, 2, wx.ALL, 2)
        box_buffer.Add(box_buffertext, 0, wx.ALIGN_RIGHT | wx.ALL, 2)

        # minfeaturesize
        minfeaturesize = wx.StaticBox(self, 1010, _("Minfeaturesize"),
	                             style = 0, name = "Minfeaturesize Box")
        box_minfeaturesize = wx.StaticBoxSizer(minfeaturesize, wx.VERTICAL)
        umn_minfeaturesize= self.umn_label.get_minfeaturesize()
        box_minfeaturesizetext = wx.BoxSizer(wx.HORIZONTAL)        
        self.text_minfeaturesize = wx.SpinCtrl(self, -1, 
                              value=str(umn_minfeaturesize), max=10, min=-1,
                              name='minfeaturesize', style=wx.SP_ARROW_KEYS)
        box_minfeaturesizetext.Add(self.text_minfeaturesize, 2, wx.ALL, 2)
        box_minfeaturesize.Add(box_minfeaturesizetext, 0, 
                                             wx.ALIGN_RIGHT | wx.ALL, 2)

        # mindistance
        mindistance = wx.StaticBox(self, 1010, _("Mindistance"), style = 0,
                                            name = "Mindistance Box",   )
        box_mindistance = wx.StaticBoxSizer(mindistance, wx.VERTICAL)
        umn_mindistance= self.umn_label.get_mindistance()
        box_mindistancetext = wx.BoxSizer(wx.HORIZONTAL)        
        self.text_mindistance = wx.SpinCtrl(self, -1, 
                              value=str(umn_mindistance), max=10, min=-1,
                              name='mindistance', style=wx.SP_ARROW_KEYS)
        box_mindistancetext.Add(self.text_mindistance, 2, wx.ALL, 2)
        box_mindistance.Add(box_mindistancetext, 0, 
                                             wx.ALIGN_RIGHT | wx.ALL, 2)
        
        # position
        umn_label_position= self.umn_label.get_position(mode="string")
        possible_choices = []
        for key in label_position_type:
            possible_choices.append(label_position_type[key])
        self.choice_position = wx.RadioBox(self, -1, choices=possible_choices,
                                          label='Position', majorDimension=1,
                                          name='position check', 
					  size=wx.DefaultSize,
	                                  style=wx.RA_SPECIFY_ROWS)
        self.choice_position.SetStringSelection(umn_label_position)
  
        #buttons
        box_buttons = wx.BoxSizer(wx.HORIZONTAL)
        button = wx.Button(self, wx.ID_OK, _("OK"))
        box_buttons.Add(button, 0, wx.ALL, 5)
        button = wx.Button(self, wx.ID_CANCEL, _("Cancel"))
        box_buttons.Add(button, 0, wx.ALL, 5)
        #set the button funcitons
        wx.EVT_BUTTON(self, wx.ID_OK, self.OnOK)
        wx.EVT_BUTTON(self, wx.ID_CANCEL, self.OnCancel)        
        
        # compose the Dialog
        top = wx.BoxSizer(wx.VERTICAL)
        
        top1 = wx.BoxSizer(wx.HORIZONTAL)
        top1.Add(box_labelsize,0, wx.EXPAND |wx.ALL, 5) 
        top1.Add(box_color,0, wx.EXPAND |wx.ALL, 5) 
        top1.Add(box_minfeaturesize,0, wx.EXPAND |wx.ALL, 5) 
        
        top2 = wx.BoxSizer(wx.HORIZONTAL)
        top2.Add(box_type,0,wx.EXPAND |wx.ALL, 5)
        top2.Add(box_offset,0, wx.EXPAND |wx.ALL, 5)   
        top2.Add(box_mindistance,0, wx.EXPAND |wx.ALL, 5) 
        
        top3 = wx.BoxSizer(wx.HORIZONTAL)
        top3.Add(self.choice_partials,0, wx.EXPAND |wx.ALL, 5) 
        top3.Add(box_buffer,0, wx.EXPAND |wx.ALL, 5) 
        top3.Add(self.choice_force,0, wx.EXPAND |wx.ALL, 5) 
        
        top.Add(top1, 0, wx.EXPAND)
        top.Add(top2, 0, wx.EXPAND)
        top.Add(top3, 0, wx.EXPAND)
        top.Add(self.choice_position,0, wx.EXPAND |wx.ALL, 5) 
        top.Add(box_buttons, 0, wx.ALIGN_RIGHT)

        # final layout settings
        self.SetSizer(top)
        top.Fit(self)
    
    def OnChangeColor(self, event):
        cur = self.umn_label.get_color().get_thubancolor()
        dialog = ColorDialog(self)
        dialog.SetColor(cur)
        self.retcolor = None
        if dialog.ShowModal() == wx.ID_OK:
            self.retcolor = dialog.GetColor()
        dialog.Destroy()
        if self.retcolor:
            self.redcolor = int(round(self.retcolor.red*255))
            self.greencolor = int(round(self.retcolor.green*255))
            self.bluecolor = int(round(self.retcolor.blue*255))
            self.previewcolor.SetBackgroundColour(wx.Colour(int(self.redcolor), 
                                                           int(self.greencolor),
					                   int(self.bluecolor)))
            # refresh the colorbox to show the new color
            self.previewcolor.Refresh()

    def RunDialog(self):
        self.ShowModal()
        self.Destroy()

    def end_dialog(self, result):
        self.result = result
        if self.result is not None:
            self.EndModal(wx.ID_OK)
        else:
            self.EndModal(wx.ID_CANCEL)
        self.Show(False)

    def OnOK(self, event):
        self.umn_label.set_size(self.text_labelsize.GetValue())
        self.umn_label.set_offset(self.text_offsetx.GetValue(),
	                          self.text_offsety.GetValue())
        self.umn_label.set_type(self.choice_type.GetStringSelection())
        if self.choice_partials.GetStringSelection() == "True":
            self.umn_label.set_partials(True)
        else:
            self.umn_label.set_partials(False)
        previewcolor = self.previewcolor.GetBackgroundColour()
        self.umn_label.get_color().set_rgbcolor(previewcolor.Red(),
                    previewcolor.Green(), previewcolor.Blue())
        self.umn_label.set_mindistance(self.text_mindistance.GetValue())
        self.umn_label.set_minfeaturesize(self.text_minfeaturesize.GetValue())
        self.umn_label.set_position(self.choice_position.GetStringSelection())
        self.umn_label.set_buffer(self.text_buffer.GetValue())
        if self.choice_force.GetStringSelection() == "True":
            self.umn_label.set_force(True)
        else:
            self.umn_label.set_force(False)
        self.result ="OK"
        self.end_dialog(self.result)

    def OnCancel(self, event):
        self.end_dialog(None)
    
class Scalebar_Dialog(wx.Dialog):
    
    def __init__(self, parent, ID, title,
                 pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=wx.DEFAULT_DIALOG_STYLE):
                     
        # initialize the Dialog
        wx.Dialog.__init__(self, parent, ID, title, pos, size, style)

        #  get the web object
        self.tb_map = parent.canvas.Map()
        self.umn_scalebar = self.tb_map.extension_umn_mapobj.get_scalebar()

        # color chooser
        box_colorStatic = wx.StaticBox(self, 1011, _("Color"),  style = 0,
	                              name = "color")
        box_color = wx.StaticBoxSizer(box_colorStatic, wx.VERTICAL)
        # preview box
        self.previewcolor = wx.Panel(self, 99, name = 'colorPanel',
	                            style = wx.SIMPLE_BORDER | wx.CLIP_CHILDREN)
        color = self.umn_scalebar.get_color()
        self.previewcolor.SetBackgroundColour(wx.Colour(color.get_red(),
        color.get_green(), color.get_blue()))
        box_color.Add(self.previewcolor, 1, wx.GROW | wx.ALL, 5)
        # color change button, opens a new color dialog
        button = wx.Button(self, ID_COLOR_CHANGE, _("Change Color"))
        button.SetFocus()
        wx.EVT_BUTTON(self, ID_COLOR_CHANGE, self.OnChangeColor)
        box_color.Add(button, 1, wx.EXPAND|wx.ALL, 5)
        # show the two color chooser horizontal
        colorHor = wx.BoxSizer(wx.HORIZONTAL)
        colorHor.Add(box_color,0, wx.EXPAND |wx.ALL, 5) 
        
        # imagecolor chooser
        box_imgcolorStatic = wx.StaticBox(self, 1011, _("Image Color"), 
	                                 style = 0, name = "imgcolor")
        box_imgcolor = wx.StaticBoxSizer(box_imgcolorStatic, wx.VERTICAL)
        # preview box
        self.previewimgcolor = wx.Panel(self, 99, name = 'colorPanel',
	                               style = wx.SIMPLE_BORDER|wx.CLIP_CHILDREN)
        color = self.umn_scalebar.get_imagecolor()
        self.previewimgcolor.SetBackgroundColour(wx.Colour(color.get_red(),
                              color.get_green(), color.get_blue()))
        box_imgcolor.Add(self.previewimgcolor, 1, wx.GROW | wx.ALL, 5)
        # color change button, opens a new color dialog
        button = wx.Button(self, ID_IMGCOLOR_CHANGE, _("Change ImageColor"))
        button.SetFocus()
        wx.EVT_BUTTON(self, ID_IMGCOLOR_CHANGE, self.OnChangeImageColor)
        box_imgcolor.Add(button, 1, wx.EXPAND|wx.ALL, 5)
        colorHor.Add(box_imgcolor,0, wx.EXPAND |wx.ALL, 5)
        
        # create the intervals
        intervalsStatic = wx.StaticBox(self, 1010, _("Intervals"), style = 0,
	                              name = "Intervals Box",   )
        box_intervals = wx.StaticBoxSizer(intervalsStatic, wx.VERTICAL)
        umn_scalebar_intervals = self.umn_scalebar.get_intervals()
        self.text_intervals = wx.SpinCtrl(self, -1, 
                              value=str(umn_scalebar_intervals), max=100, min=0,
                              name='intervals', style=wx.SP_ARROW_KEYS)
        box_intervals.Add(self.text_intervals, 0, wx.ALIGN_RIGHT | wx.ALL, 2)
        hori2 = wx.BoxSizer(wx.HORIZONTAL)
        hori2.Add(box_intervals,0, wx.EXPAND |wx.ALL, 5)

        #style
        umn_scalebar_style= self.umn_scalebar.get_style()
        possible_choices = []
        for key in scalebar_style_type:
            possible_choices.append(scalebar_style_type[key])
        self.choice_style = wx.RadioBox(self, -1, choices=possible_choices,
              label='Style', majorDimension=1,
              name='style check', size=wx.DefaultSize, style=wx.RA_SPECIFY_ROWS)
        self.choice_style.SetSelection(umn_scalebar_style)
        hori2.Add(self.choice_style, 1, wx.EXPAND|wx.ALL, 5)
        
        #create size settings
        try:
            insidetxt = self.umn_scalebar.get_size()
        except:
            insidetxt = (0,0)
        # create the Size Box
        staticSize = wx.StaticBox(self, -1, _("Size"), style = 0, 
	                         name="sizeBox")
        box_size = wx.StaticBoxSizer(staticSize, wx.HORIZONTAL)
        
        box_sizepartWidth = wx.BoxSizer(wx.HORIZONTAL)
        box_sizepartWidth.Add(wx.StaticText(self, -1, _("Width: ")), 0, wx.ALL, 4)
        self.text_width = wx.TextCtrl(self, -1, str(insidetxt[0]))
        box_sizepartWidth.Add(self.text_width, 2, wx.ALL, 4)
        box_size.Add(box_sizepartWidth, 0, wx.ALIGN_RIGHT | wx.ALL, 5)
        box_sizepartHeight = wx.BoxSizer(wx.HORIZONTAL)
        box_sizepartHeight.Add(wx.StaticText(self, -1, _("Height: ")), 0,
	                                    wx.ALL, 4)
        self.text_height = wx.TextCtrl(self, -1, str(insidetxt[1]))
        box_sizepartHeight.Add(self.text_height, 2, wx.ALL, 4)
        box_size.Add(box_sizepartHeight, 0, wx.ALIGN_RIGHT | wx.ALL, 5)
        
        # status
        umn_scalebar_status= self.umn_scalebar.get_status(mode="string")
        possible_choices = []
        for key in legend_status_type:
            possible_choices.append(scalebar_status_type[key])
        self.choice_status = wx.RadioBox(self, -1, choices=possible_choices,
              label='Status', majorDimension=1,
              name='status check', size=wx.DefaultSize, style=wx.RA_SPECIFY_ROWS)
        self.choice_status.SetStringSelection(umn_scalebar_status)
        
        # position
        umn_scalebar_position= self.umn_scalebar.get_position(mode="string")
        possible_choices = []
        for key in scalebar_position_type:
            possible_choices.append(scalebar_position_type[key])
        self.choice_position = wx.RadioBox(self, -1, choices=possible_choices,
                                      label='Position', majorDimension=1,
                                      name='position check', size=wx.DefaultSize,
	                              style=wx.RA_SPECIFY_ROWS)
        self.choice_position.SetStringSelection(umn_scalebar_position)
        
        #get the set unittype
        insideunit = self.umn_scalebar .get_units()
        #create the Unittype selector
        box_unitsStatic = wx.StaticBox(self, -1, _("Unit Type"),  style = 0,
	                              name = "unittype")
        box_units = wx.StaticBoxSizer(box_unitsStatic, wx.VERTICAL)
        sam = []
        for key in unit_type:
            sam.append(unit_type[key])
        self.choice_units = wx.Choice(self, 40, (80, 50), choices = sam)
        self.choice_units.SetStringSelection(insideunit)
        box_units.Add(self.choice_units,0, wx.EXPAND, wx.ALL, 5)    
        
        # button for label
        labelbutton = wx.Button(self, ID_LABEL_CHANGE, _("Change Label"))
        wx.EVT_BUTTON(self, ID_LABEL_CHANGE, self.OnChangeLabel)
        
        #buttons
        box_buttons = wx.BoxSizer(wx.HORIZONTAL)
        button = wx.Button(self, wx.ID_OK, _("OK"))
        box_buttons.Add(button, 0, wx.ALL, 5)
        button = wx.Button(self, wx.ID_CANCEL, _("Cancel"))
        button.SetFocus()
        box_buttons.Add(button, 0, wx.ALL, 5)
        #set the button funcitons
        wx.EVT_BUTTON(self, wx.ID_OK, self.OnOK)
        wx.EVT_BUTTON(self, wx.ID_CANCEL, self.OnCancel)      
      
        # compose the dialog
        top = wx.BoxSizer(wx.VERTICAL)
        top.Add(colorHor,0, wx.EXPAND |wx.ALL, 5)
        top.Add(hori2, 1, wx.EXPAND|wx.ALL, 5)
        top.Add(box_size, 1, wx.EXPAND|wx.ALL, 5)
        top.Add(self.choice_status,0, wx.EXPAND |wx.ALL, 5) 
        top.Add(self.choice_position,0, wx.EXPAND |wx.ALL, 5) 
        top.Add(box_units, 1, wx.EXPAND|wx.ALL, 5)
        top.Add(labelbutton, 0, wx.EXPAND|wx.ALL, 5)
        top.Add(box_buttons, 0, wx.ALIGN_RIGHT)
        
        # final layout settings
        self.SetSizer(top)
        top.Fit(self)
    
    def OnChangeLabel(self, event):
        # set the umn_label for scalebar so the Label_Dialog can be used
        self.umn_label = self.umn_scalebar.get_label()
        dialog = Label_Dialog(self, -1, "Scalbar Label Settings",
	                      size=wx.Size(350, 200),
                 style = wx.DEFAULT_DIALOG_STYLE
                 )
        dialog.CenterOnScreen()
        if dialog.ShowModal() == wx.ID_OK:
            return
        dialog.Destroy()

    def OnChangeImageColor(self, event):
        cur = self.umn_scalebar.get_imagecolor().get_thubancolor()
        dialog = ColorDialog(self)
        dialog.SetColor(cur)
        self.retcolor = None
        if dialog.ShowModal() == wx.ID_OK:
            self.retcolor = dialog.GetColor()
        dialog.Destroy()
        if self.retcolor:
            self.redcolor = int(round(self.retcolor.red*255))
            self.greencolor = int(round(self.retcolor.green*255))
            self.bluecolor = int(round(self.retcolor.blue*255))
            self.previewimgcolor.SetBackgroundColour(wx.Colour(int(self.redcolor), 
                                                           int(self.greencolor),
							   int(self.bluecolor)))
            # refresh the colorbox to show the new color
            self.previewimgcolor.Refresh()

    def OnChangeColor(self, event):
        cur = self.umn_scalebar.get_color().get_thubancolor()
        dialog = ColorDialog(self)
        dialog.SetColor(cur)
        self.retcolor = None
        if dialog.ShowModal() == wx.ID_OK:
            self.retcolor = dialog.GetColor()
        dialog.Destroy()
        if self.retcolor:
            self.redcolor = int(round(self.retcolor.red*255))
            self.greencolor = int(round(self.retcolor.green*255))
            self.bluecolor = int(round(self.retcolor.blue*255))
            self.previewcolor.SetBackgroundColour(wx.Colour(int(self.redcolor), 
                                                           int(self.greencolor),
					                   int(self.bluecolor)))
            # refresh the colorbox to show the new color
            self.previewcolor.Refresh()

    def RunDialog(self):
        self.ShowModal()
        self.Destroy()

    def end_dialog(self, result):
        self.result = result
        if self.result is not None:
            self.EndModal(wx.ID_OK)
        else:
            self.EndModal(wx.ID_CANCEL)
        self.Show(False)

    def OnOK(self, event):
        self.umn_scalebar.set_status(self.choice_status.GetStringSelection())
        self.umn_scalebar.set_units(self.choice_units.GetStringSelection())
        self.umn_scalebar.set_intervals(self.text_intervals.GetValue())
        self.umn_scalebar.set_style(self.choice_style.GetSelection())
        self.umn_scalebar.set_position(self.choice_position.GetStringSelection())
        self.umn_scalebar.set_size(int(self.text_width.GetValue()), 
	                           int(self.text_height.GetValue()))

        previewcolor = self.previewcolor.GetBackgroundColour()
        self.umn_scalebar.get_color().set_rgbcolor(previewcolor.Red(),
                    previewcolor.Green(), previewcolor.Blue())
        previewimgcolor = self.previewimgcolor.GetBackgroundColour()
        self.umn_scalebar.get_imagecolor().set_rgbcolor(previewimgcolor.Red(),
                    previewimgcolor.Green(), previewimgcolor.Blue())
        self.result ="OK"
        self.end_dialog(self.result)

    def OnCancel(self, event):
        self.end_dialog(None)


class Metadata_CustomDataTable(grid.PyGridTableBase):
    """
    creates a custum Grid.
    
    copied from the wx. demo.
    """
    def __init__(self, data):
        grid.PyGridTableBase.__init__(self)

        self.colLabels = ['ID', 'Description']
        self.dataTypes = [grid.GRID_VALUE_STRING,
                          grid.GRID_VALUE_STRING
                          ]
        
        if data:
            self.data = data
        else:
            self.data = [["",""]]    #--------------------------------------------------
    # required methods for the grid.PyGridTableBase interface

    def GetNumberRows(self):
        return len(self.data) + 1

    def GetNumberCols(self):
        return len(self.data[0])

    def IsEmptyCell(self, row, col):
        try:
            return not self.data[row][col]
        except IndexError:
            return True

    # Get/Set values in the table.  The Python version of these
    # methods can handle any data-type, (as long as the Editor and
    # Renderer understands the type too,) not just strings as in the
    # C++ version.
    def GetValue(self, row, col):
        try:
            return self.data[row][col]
        except IndexError:
            return ''

    def SetValue(self, row, col, value):
        try:
            self.data[row][col] = value
        except IndexError:
            # add a new row
            
            self.data.append([''] * self.GetNumberCols())
            self.SetValue(row, col, value)

            # tell the grid we've added a row
            msg = grid.GridTableMessage(self,                             # The table
                                     grid.GRIDTABLE_NOTIFY_ROWS_APPENDED, # what we did to it
                                     1)                                # how many

            self.GetView().ProcessTableMessage(msg)

    #--------------------------------------------------
    # Some optional methods

    # Called when the grid needs to display labels
    def GetColLabelValue(self, col):
        return self.colLabels[col]

    # Called to determine the kind of editor/renderer to use by
    # default, doesn't necessarily have to be the same type used
    # natively by the editor/renderer if they know how to convert.
    def GetTypeName(self, row, col):
        return self.dataTypes[col]

    # Called to determine how the data can be fetched and stored by the
    # editor and renderer.  This allows you to enforce some type-safety
    # in the grid.
    def CanGetValueAs(self, row, col, typeName):
        colType = self.dataTypes[col].split(':')[0]
        if typeName == colType:
            return True
        else:
            return False

    def CanSetValueAs(self, row, col, typeName):
        return self.CanGetValueAs(row, col, typeName)


class Metadata_TableGrid(grid.Grid):
    def __init__(self, parent, data):
        grid.Grid.__init__(self, parent, -1)

        self.table = Metadata_CustomDataTable(data)

        # The second parameter means that the grid is to take ownership of the
        # table and will destroy it when done.  Otherwise you would need to keep
        # a reference to it and call it's Destroy method later.
        self.SetTable(self.table, True)

        self.SetRowLabelSize(0)
        self.SetColMinimalWidth(0,180)
        self.SetColSize(0,180)
        self.SetColMinimalWidth(1,250)
        self.SetColSize(1,250)
        self.SetMargins(0,0)
        grid.EVT_GRID_CELL_LEFT_DCLICK(self, self.OnLeftDClick)

    def get_table(self):
        return self.table

    # I do this because I don't like the default behaviour of not starting the
    # cell editor on double clicks, but only a second click.
    def OnLeftDClick(self, evt):
        if self.CanEnableCellControl():
            self.EnableCellEditControl()


class Metadata_Dialog(wx.Dialog):
    
    def __init__(self, parent, ID, title,
                 pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=wx.DEFAULT_DIALOG_STYLE):
                     
        # initialize the Dialog
        wx.Dialog.__init__(self, parent, ID, title, pos, size, style)
        
        #  get the web object
        if hasattr(parent,"umn_metadata"):
            self.umn_metadata = parent.umn_metadata
        else:
            self.tb_map = parent.canvas.Map()
            self.umn_metadata = self.tb_map.extension_umn_mapobj.get_metadata()
        
        
        # at all items to the dataset
        self.grid = Metadata_TableGrid(self, self.umn_metadata.get_metadata())
        
        #buttons
        box_buttons = wx.BoxSizer(wx.HORIZONTAL)
        button = wx.Button(self, wx.ID_OK, _("OK"))
        box_buttons.Add(button, 0, wx.ALL, 5)
        button = wx.Button(self, wx.ID_CANCEL, _("Cancel"))
        button.SetFocus()
        box_buttons.Add(button, 0, wx.ALL, 5)
        #set the button funcitons
        wx.EVT_BUTTON(self, wx.ID_OK, self.OnOK)
        wx.EVT_BUTTON(self, wx.ID_CANCEL, self.OnCancel)      
        
        # compose the dialog
        top = wx.BoxSizer(wx.VERTICAL)
        top.Add(self.grid, 1, wx.GROW|wx.ALL, 5)
        top.Add(box_buttons, 0, wx.ALIGN_RIGHT)
        
        # final layout settings
        self.SetSizer(top)
        #top.Fit(self)
        
    def OnItemActivated(self, event):
        self.currentItem = event.m_itemIndex

    def OnDoubleClick(self, event):
        print "OnDoubleClick" +self.list.GetItemText(self.currentItem)
        event.Skip()
        
    def OnSize(self, event):
        w,h = self.GetClientSizeTuple()
        self.list.SetDimensions(0, 0, w, h)
        
    def RunDialog(self):
        self.ShowModal()
        self.Destroy()

    def end_dialog(self, result):
        self.result = result
        if self.result is not None:
            self.EndModal(wx.ID_OK)
        else:
            self.EndModal(wx.ID_CANCEL)
        self.Show(False)

    def OnOK(self, event):
        # added all metadatas to the mapobj,
        # first remove the old ones
        self.umn_metadata.remove_allmetadata()
        for x in range(self.grid.get_table().GetNumberRows()-2,-1, -1):
            if self.grid.get_table().GetValue(x,0):
                self.umn_metadata.add_metadata(str(self.grid.get_table().GetValue(x,0)),\
                     str(self.grid.get_table().GetValue(x,1)))

        self.result ="OK"
        self.end_dialog(self.result)

    def OnCancel(self, event):
        self.end_dialog(None)
        
        
        

def metadatasettings(context):
    win = Metadata_Dialog(context.mainwindow, -1, "Metadata Settings",
                          size=wx.Size(450, 250),
                          style = wx.DEFAULT_DIALOG_STYLE)
    win.CenterOnScreen()
    val = win.ShowModal()    
    

def scalebarsettings(context):
    win = Scalebar_Dialog(context.mainwindow, -1, "Scalebar Settings",
                          size=wx.Size(350, 200),
                          style = wx.DEFAULT_DIALOG_STYLE)
    win.CenterOnScreen()
    val = win.ShowModal()

def mapsettings(context):
    win = Map_Dialog(context.mainwindow, -1, "Map Settings",
                     size=wx.Size(350, 200),
                     style = wx.DEFAULT_DIALOG_STYLE)
    win.CenterOnScreen()
    val = win.ShowModal()

def outputformatsettings(context):
    win = OutputFormat_Dialog(context.mainwindow, -1, "OutputFormat Settings", 
                              size=wx.Size(350, 200),
		              style = wx.DEFAULT_DIALOG_STYLE)
    win.CenterOnScreen()
    val = win.ShowModal()

def websettings(context):
    win = Web_Dialog(context.mainwindow, -1, "Web Settings",
                     size=wx.Size(350, 200),
                     style = wx.DEFAULT_DIALOG_STYLE)
    win.CenterOnScreen()
    val = win.ShowModal()

def layersettings(context):
    win = Layer_Dialog(context.mainwindow, -1, "Layer Settings",
                     size=wx.Size(350, 200),
                     style = wx.DEFAULT_DIALOG_STYLE)
    win.CenterOnScreen()
    val = win.ShowModal()

def legendsettings(context):
    win = Legend_Dialog(context.mainwindow, -1, "Legend Settings",
                        size=wx.Size(350, 200),
                        style = wx.DEFAULT_DIALOG_STYLE)
    win.CenterOnScreen()
    val = win.ShowModal()

# TODO: Maybe can be imported from another class
# check if an mapobj exists, to control the menuitem is available or not
def _has_umn_mapobj(context):
    """Return true if a umn_mapobj exists"""
    return hasattr(context.mainwindow.canvas.Map(), "extension_umn_mapobj")

def _has_umn_mapobj_and_selectedlayer(context):
    """Return true if a umn_mapobj exists"""
    # temporary disabled
    #return False
    if context.mainwindow.has_selected_layer():
        return hasattr(context.mainwindow.canvas.Map(), "extension_umn_mapobj")
    else:
        return False

# ###################################
#
# Hook in MapServer Extension into Thuban
#
# ###################################

# find the extensions menu (create it anew if not found)
experimental_menu = main_menu.FindOrInsertMenu("experimental",
                                             _("Experimenta&l"))
# find the extension menu and add a new submenu if found
mapserver_menu = experimental_menu.FindOrInsertMenu("mapserver",
                                                  _("&MapServer"))

# find the MapServer menu and add a new submenu if found
mapserver_edit_menu = mapserver_menu.FindOrInsertMenu("edit_mapfile",
                                                  _("&Edit mapfile"), \
                                                  after = "import_layer_from_mapfile")

# register the new command (Map Settings Dialog)
registry.Add(Command("Map Settings", _("Map"), mapsettings,
                     helptext = _("Edit the Map Setting"), \
                     sensitive = _has_umn_mapobj))
# finally add the new entry to the extensions menu
mapserver_edit_menu.InsertItem("Map Settings")


# register the new command (Map Settings Dialog)
registry.Add(Command("Web Settings", _("Web"),
                     websettings,
                     helptext = _("Edit the Web Setting"), \
                     sensitive = _has_umn_mapobj))
# finally add the new entry to the extensions menu
mapserver_edit_menu.InsertItem("Web Settings")

# register the new command (Layer Settings Dialog)
registry.Add(Command("Layer Settings", _("Layer"),
                     layersettings,
                     helptext = _("Edit the Layer Setting of the active Layer"), \
                     sensitive = _has_umn_mapobj_and_selectedlayer))
# finally add the new entry to the extensions menu
mapserver_edit_menu.InsertItem("Layer Settings")

# register the new command (Legend Settings Dialog)
registry.Add(Command("Legend Settings", _("Legend"),
                     legendsettings,
                     helptext = _("Edit the Legend Setting"), \
                     sensitive = _has_umn_mapobj))
# finally add the new entry to the extensions menu
mapserver_edit_menu.InsertItem("Legend Settings")

# register the new command (Scalebar Settings Dialog)
registry.Add(Command("Scalebar Settings", _("Scalebar"),
                     scalebarsettings,
                     helptext = _("Edit the Scalebar Setting"), \
                     sensitive = _has_umn_mapobj))
# finally add the new entry to the extensions menu
mapserver_edit_menu.InsertItem("Scalebar Settings")

# register the new command (Scalebar Settings Dialog)
registry.Add(Command("Metadata Settings", _("Metadata"),
                     metadatasettings,
                     helptext = _("Edit the Metadata Setting"), \
                     sensitive = _has_umn_mapobj))
# finally add the new entry to the extensions menu
mapserver_edit_menu.InsertItem("Metadata Settings")


