# -*- coding:latin1 -*-
# 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: 1.8 $"
# $Source: /thubanrepository/thuban/Extensions/umn_mapserver/mf_handle.py,v $
# $Id: mf_handle.py,v 1.8 2004/08/09 11:40:10 jschuengel Exp $


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

import os, sys

# mapscript
from mapscript import mapObj, layerObj

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

# 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(wxDialog):
    
    def __init__(self, parent, ID, title,
                 pos=wxDefaultPosition, size=wxDefaultSize,
                 style=wxDEFAULT_DIALOG_STYLE):
                     
        # initialize the Dialog
        wxDialog.__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 = wxBoxSizer(wxHORIZONTAL)
        box_name.Add(wxStaticText(self, -1, _("Map-Name:")), 0,
                     wxALL|wxALIGN_CENTER_VERTICAL, 4)
        box_name.Add(wxStaticText(self, -1, self.tb_map.Title()), 0,
                     wxALL|wxALIGN_CENTER_VERTICAL, 4)  

        #create size settings
        insidetxt = self.tb_map_umn.get_size()
        staticSize = wxStaticBox(self, 1010, _("Size"), style = 0, 
	                         name = "staticBox",   )
        box_size = wxStaticBoxSizer(staticSize, wxVERTICAL)
        
        box_sizepartWidth = wxBoxSizer(wxHORIZONTAL)
        box_sizepartWidth.Add(wxStaticText(self, -1, _("Width: ")), 0, wxALL, 4)
        self.text_width = wxTextCtrl(self, -1, str(insidetxt[0]))
        box_sizepartWidth.Add(self.text_width, 2, wxALL, 4)
        box_size.Add(box_sizepartWidth, 0, wxALIGN_RIGHT | wxALL, 5)
        box_sizepartHeight = wxBoxSizer(wxHORIZONTAL)
        box_sizepartHeight.Add(wxStaticText(self, -1, _("Height: ")), 0,
	                                    wxALL, 4)
        self.text_height = wxTextCtrl(self, -1, str(insidetxt[1]))
        box_sizepartHeight.Add(self.text_height, 2, wxALL, 4)
        box_size.Add(box_sizepartHeight, 0, wxALIGN_RIGHT | wxALL, 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 = wxStaticBox(self, -1, _("Image Type"),
                                          style = 0, name = "imagetype")
        box_imagetype = wxStaticBoxSizer(box_imagetypeStatic, wxVERTICAL)
        self.choice_imgtype = wxChoice(self, 8060, (80, 50), 
                                        choices = umn_outputformats)
        EVT_CHOICE(self, 8060, self.EvtChoiceBox)
        self.choice_imgtype.SetStringSelection(umn_imagetype)
        box_imagetype.Add(self.choice_imgtype,0, wxEXPAND, wxALL, 5)    
        
        #unittype
        insideunit = self.tb_map_umn.get_units()
        #Unittype selector
        box_unitsStatic = wxStaticBox(self, 1011, _("Unit Type"),
	                              style = 0, name = "imagecolor")
        box_units = wxStaticBoxSizer(box_unitsStatic, wxVERTICAL)
        sam = []
        for key in unit_type:
            sam.append(unit_type[key])
        self.choice_units = wxChoice(self, 40, (80, 50), choices = sam)
        self.choice_units.SetStringSelection(insideunit)
        box_units.Add(self.choice_units,0, wxEXPAND, wxALL, 5)        
    
        # color chouser
        box_colorStatic = wxStaticBox(self, 1011, _("ImageColor"),
	                              style = 0, name = "imagecolor")
        box_color = wxStaticBoxSizer(box_colorStatic, wxVERTICAL)
        
        # preview box
        self.previewcolor = wxPanel(self,99, name = 'backgroundPanel',
	                            style = wxSIMPLE_BORDER | wxCLIP_CHILDREN)
        imagecolor = self.tb_map_umn.get_imagecolor()
        self.previewcolor.SetBackgroundColour(wxColour(imagecolor.get_red(),
        imagecolor.get_green(), imagecolor.get_blue()))
        box_color.Add(self.previewcolor, 1, wxGROW | wxALL, 5)
        # color change button, opens a new color dialog
        button = wxButton(self, ID_COLOR_CHANGE, _("Change Color"))
        button.SetFocus()
        EVT_BUTTON(self, ID_COLOR_CHANGE, self.OnChangeColor)
        box_color.Add(button, 1, wxEXPAND|wxALL, 5)
        
        # status
        umn_status = self.tb_map_umn.get_status()
        self.choice_status = wxRadioBox(self, -1, choices=["True","False"],
              label='status', majorDimension=1,
              name='status check', size=wxDefaultSize, style=wxRA_SPECIFY_ROWS)
        self.choice_status.SetStringSelection(str(umn_status))
        
        #buttons
        box_buttons = wxBoxSizer(wxHORIZONTAL)
        button = wxButton(self, wxID_OK, _("OK"))
        box_buttons.Add(button, 0, wxALL, 5)
        button = wxButton(self, wxID_CANCEL, _("Cancel"))
        box_buttons.Add(button, 0, wxALL, 5)
        #button functions
        EVT_BUTTON(self, wxID_OK, self.OnOK)
        EVT_BUTTON(self, wxID_CANCEL, self.OnCancel)
        
        #add all boxes to the box top
        top = wxBoxSizer(wxVERTICAL)
        top.Add(box_name, 0, wxEXPAND |wxALL, 5)
        top.Add(box_size, 0, wxEXPAND |wxALL, 5)
        top.Add(box_imagetype,0, wxEXPAND |wxALL, 5)
        top.Add(box_units,0, wxEXPAND |wxALL, 5)
        top.Add(box_color,0, wxEXPAND |wxALL, 5)     
        top.Add(self.choice_status,0, wxEXPAND |wxALL, 5)   
        top.Add(box_buttons, 0, wxALIGN_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() == wxID_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(wxColour((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(wxID_OK)
        else:
            self.EndModal(wxID_CANCEL)
        self.Show(False)

    def OnOK(self, event):
        self.tb_map_umn.set_size(int(self.text_width.GetValue()), 
                                 int(self.text_height.GetValue()))
        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(wxDialog):
        
    def __init__(self, parent, ID, title,
                 pos=wxDefaultPosition, size=wxDefaultSize,
                 style=wxDEFAULT_DIALOG_STYLE):
                     
        # initialize the Dialog
        wxDialog.__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 = wxBoxSizer(wxHORIZONTAL)
        box_template.Add(wxStaticText(self, -1, _("Template:")), 0,
                     wxALL|wxALIGN_LEFT, 4)
        self.text_template = wxTextCtrl(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,
                     wxALL|wxALIGN_CENTER_VERTICAL, 4)  
    
        # Imagepath 
        box_imagepath = wxBoxSizer(wxHORIZONTAL)
        box_imagepath.Add(wxStaticText(self, -1, _("Imagepath:")), 0,
                     wxALL|wxALIGN_LEFT, 4)
        self.text_imagepath = wxTextCtrl(self, -1, 
	                                 str(self.umn_web.get_imagepath()))
        box_imagepath.Add(self.text_imagepath, 0,
                     wxALL|wxALIGN_CENTER_VERTICAL, 4)  

        # Imageurl 
        box_imageurl = wxBoxSizer(wxHORIZONTAL)
        box_imageurl.Add(wxStaticText(self, -1, _("Imageurl:")), 0,
                     wxALL|wxALIGN_LEFT, 4)
        self.text_imageurl = wxTextCtrl(self, -1, 
                                    str(self.umn_web.get_imageurl()))
        box_imageurl.Add(self.text_imageurl, 0,
                     wxALL|wxALIGN_CENTER_VERTICAL, 4)  
        
        #buttons
        box_buttons = wxBoxSizer(wxHORIZONTAL)
        button = wxButton(self, wxID_OK, _("OK"))
        box_buttons.Add(button, 0, wxALL, 5)
        button = wxButton(self, wxID_CANCEL, _("Cancel"))
        box_buttons.Add(button, 0, wxALL, 5)
        #set the button funcitons
        EVT_BUTTON(self, wxID_OK, self.OnOK)
        EVT_BUTTON(self, wxID_CANCEL, self.OnCancel)      
      
        # compose the final dialog
        top = wxBoxSizer(wxVERTICAL)
        top.Add(box_template, 0, wxEXPAND |wxALL, 5)
        top.Add(box_imagepath, 0, wxEXPAND |wxALL, 5)
        top.Add(box_imageurl, 0, wxEXPAND |wxALL, 5)
        top.Add(box_buttons, 0, wxALIGN_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(wxID_OK)
        else:
            self.EndModal(wxID_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(wxDialog):
        
    def __init__(self, parent, ID, title,
                 pos=wxDefaultPosition, size=wxDefaultSize,
                 style=wxDEFAULT_DIALOG_STYLE):
                     
        # initialize the Dialog
        wxDialog.__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 = wxBoxSizer(wxHORIZONTAL)
        layer_name.Add(wxStaticText(self, -1, _("Layer-Name:")), 0,
                     wxALL|wxALIGN_CENTER_VERTICAL, 4)
        layer_name.Add(wxStaticText(self, -1, self.tb_layer.Title()), 0,
                     wxALL|wxALIGN_CENTER_VERTICAL, 4)  
 
        # metadata button
        metadata_button = wxButton(self, ID_METADATA_CHANGE, _("Edit Metadata"))
        EVT_BUTTON(self, ID_METADATA_CHANGE, self.OnChangeMetadata)
        
        # Group 
        box_group = wxBoxSizer(wxHORIZONTAL)
        if self.umn_layer.get_group():
            umn_layer_group = self.umn_layer.get_group()
        else:
            umn_layer_group = ""
        box_group.Add(wxStaticText(self, -1, _("Group:")), 0,
                     wxALL|wxALIGN_LEFT, 4)
        self.text_group = wxTextCtrl(self, -1, 
                                    str(umn_layer_group))
        self.text_group.SetSize((250,self.text_group.GetSize()[1]))
        box_group.Add(self.text_group, 0,
                     wxALL|wxALIGN_CENTER_VERTICAL, 4)  
        
        # buttons
        box_buttons = wxBoxSizer(wxHORIZONTAL)
        button = wxButton(self, wxID_OK, _("OK"))
        box_buttons.Add(button, 0, wxALL, 5)
        button = wxButton(self, wxID_CANCEL, _("Cancel"))
        box_buttons.Add(button, 0, wxALL, 5)
        #set the button funcitons
        EVT_BUTTON(self, wxID_OK, self.OnOK)
        EVT_BUTTON(self, wxID_CANCEL, self.OnCancel)      
      
        # compose the final dialog
        top = wxBoxSizer(wxVERTICAL)
        #top.Add(box_template, 0, wxEXPAND |wxALL, 5)
        top.Add(layer_name, 0, wxEXPAND|wxALL, 5)
        top.Add(box_group, 0, wxEXPAND|wxALL, 5)
        top.Add(metadata_button, 0, wxEXPAND|wxALL, 5)
        top.Add(box_buttons, 0, wxALIGN_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=wxSize(450, 200),
                 style = wxDEFAULT_DIALOG_STYLE
                 )
        dialog.CenterOnScreen()
        if dialog.ShowModal() == wxID_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(wxID_OK)
        else:
            self.EndModal(wxID_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(wxDialog):
        
    def __init__(self, parent, ID, title,
                 pos=wxDefaultPosition, size=wxDefaultSize,
                 style=wxDEFAULT_DIALOG_STYLE):
                     
        # initialize the Dialog
        wxDialog.__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 = wxStaticBox(self, 1010, _("KeySize"), style = 0,
	                      name = "KeySize Box",   )
        box_keysize = wxStaticBoxSizer(keySize, wxVERTICAL)
        umn_legend_keysize = self.umn_legend.get_keysize()
        box_sizepartWidth = wxBoxSizer(wxHORIZONTAL)        
        box_sizepartWidth.Add(wxStaticText(self, -1, _("Width: ")), 0, wxALL, 2)
        self.text_keysize_width = wxSpinCtrl(self, -1, 
                              value=str(umn_legend_keysize[0]), max=100, min=0,
                              name='keywidth', style=wxSP_ARROW_KEYS)
        box_sizepartWidth.Add(self.text_keysize_width, 2, wxALL, 2)
        box_keysize.Add(box_sizepartWidth, 0, wxALIGN_RIGHT | wxALL, 2)
        box_sizepartHeight = wxBoxSizer(wxHORIZONTAL)
        box_sizepartHeight.Add(wxStaticText(self, -1, _("Height: ")), 0, wxALL, 2),
        self.text_keysize_height = wxSpinCtrl(self, -1, 
                              value=str(umn_legend_keysize[1]), max=100, min=0,
                              name='keyheight', style=wxSP_ARROW_KEYS)
        box_sizepartHeight.Add(self.text_keysize_height, 2, wxALL, 2)
        box_keysize.Add(box_sizepartHeight, 0, wxALIGN_RIGHT | wxALL, 2)
        
        # create the Keyspacing
        keySpacing= wxStaticBox(self, 1010, _("KeySpacing"), style = 0,
	                        name = "KeySpacing Box",   )
        box_keyspacing = wxStaticBoxSizer(keySpacing, wxVERTICAL)
        umn_legend_keyspacing = self.umn_legend.get_keyspacing()
        box_sizepartWidth = wxBoxSizer(wxHORIZONTAL)        
        box_sizepartWidth.Add(wxStaticText(self, -1, _("Width: ")), 0, wxALL, 2)
        self.text_keyspacing_width = wxSpinCtrl(self, -1, 
                              value=str(umn_legend_keyspacing[0]), max=100,
			      min=0, name='spacingwidth', style=wxSP_ARROW_KEYS)
        box_sizepartWidth.Add(self.text_keyspacing_width, 2, wxALL, 2)
        box_keyspacing.Add(box_sizepartWidth, 0, wxALIGN_RIGHT | wxALL, 2)
        box_sizepartHeight = wxBoxSizer(wxHORIZONTAL)
        box_sizepartHeight.Add(wxStaticText(self, -1, _("Height: ")), 0, wxALL, 2),
        self.text_keyspacing_height = wxSpinCtrl(self, -1, 
                              value=str(umn_legend_keyspacing[1]), max=100,
			      min=0,name='spacingheight', style=wxSP_ARROW_KEYS)
        box_sizepartHeight.Add(self.text_keyspacing_height, 2, wxALL, 2)
        box_keyspacing.Add(box_sizepartHeight, 0, wxALIGN_RIGHT | wxALL, 2)

        # color chooser
        box_colorStatic = wxStaticBox(self, 1011, _("ImageColor"),  style = 0,
	                              name = "imagecolor")
        box_color = wxStaticBoxSizer(box_colorStatic, wxVERTICAL)
        # preview box
        self.previewcolor = wxPanel(self, 99, name = 'imagecolorPanel',
	                            style = wxSIMPLE_BORDER | wxCLIP_CHILDREN)
        imagecolor = self.umn_legend.get_imagecolor()
        self.previewcolor.SetBackgroundColour(wxColour(imagecolor.get_red(),
        imagecolor.get_green(), imagecolor.get_blue()))
        box_color.Add(self.previewcolor, 1, wxGROW | wxALL, 5)
        # color change button, opens a new color dialog
        button = wxButton(self, ID_COLOR_CHANGE, _("Change Color"))
        button.SetFocus()
        EVT_BUTTON(self, ID_COLOR_CHANGE, self.OnChangeColor)
        box_color.Add(button, 1, wxEXPAND|wxALL, 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 = wxRadioBox(self, -1, choices=possible_choices,
              label='Status', majorDimension=1,
              name='status check', size=wxDefaultSize, style=wxRA_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 = wxRadioBox(self, -1, choices=possible_choices,
                                          label='Position', majorDimension=1,
                                          name='position check', 
					  size=wxDefaultSize,
					  style=wxRA_SPECIFY_ROWS)
        self.choice_position.SetStringSelection(umn_legend_position)
        
        # button for label
        labelbutton = wxButton(self, ID_LABEL_CHANGE, _("Change Label"))
        EVT_BUTTON(self, ID_LABEL_CHANGE, self.OnChangeLabel)
        
        #buttons
        box_buttons = wxBoxSizer(wxHORIZONTAL)
        button = wxButton(self, wxID_OK, _("OK"))
        box_buttons.Add(button, 0, wxALL, 5)
        button = wxButton(self, wxID_CANCEL, _("Cancel"))
        box_buttons.Add(button, 0, wxALL, 5)
        #set the button funcitons
        EVT_BUTTON(self, wxID_OK, self.OnOK)
        EVT_BUTTON(self, wxID_CANCEL, self.OnCancel)        
        
        # compose the final layout
        top = wxBoxSizer(wxVERTICAL)
        top.Add(box_keysize,0, wxEXPAND |wxALL, 5) 
        top.Add(box_keyspacing,0, wxEXPAND |wxALL, 5) 
        top.Add(box_color,0, wxEXPAND |wxALL, 5) 
        top.Add(self.choice_status,0, wxEXPAND |wxALL, 5) 
        top.Add(self.choice_position,0, wxEXPAND |wxALL, 5) 
        top.Add(labelbutton, 1, wxEXPAND|wxALL, 5)
        top.Add(box_buttons, 0, wxALIGN_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=wxSize(350, 200),
                 style = wxDEFAULT_DIALOG_STYLE
                 )
        dialog.CenterOnScreen()
        if dialog.ShowModal() == wxID_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() == wxID_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(wxColour(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(wxID_OK)
        else:
            self.EndModal(wxID_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(wxDialog):
    
    def __init__(self, parent, ID, title,
                 pos=wxDefaultPosition, size=wxDefaultSize,
                 style=wxDEFAULT_DIALOG_STYLE):
                     
        # initialize the Dialog
        wxDialog.__init__(self, parent, ID, title, pos, size, style)

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

        # size
        labelsize= wxStaticBox(self, 1010, _("Size"), style = 0,
	                       name = "Size Box",   )
        box_labelsize = wxStaticBoxSizer(labelsize, wxVERTICAL)
        umn_label_size= self.umn_label.get_size()
        box_size = wxBoxSizer(wxHORIZONTAL)        
        self.text_labelsize = wxSpinCtrl(self, -1, 
                              value=str(umn_label_size), max=10, min=0,
                              name='size', style=wxSP_ARROW_KEYS)
        box_size.Add(self.text_labelsize, 2, wxALL, 2)
        box_labelsize.Add(box_size, 0, wxALIGN_RIGHT | wxALL, 2)

        # color chooser
        box_colorStatic = wxStaticBox(self, 1011, _("Color"),  style = 0,
	                              name = "color")
        box_color = wxStaticBoxSizer(box_colorStatic, wxVERTICAL)
        # preview box
        self.previewcolor = wxPanel(self, 99, name = 'colorPanel',
	                            style = wxSIMPLE_BORDER | wxCLIP_CHILDREN)
        color = self.umn_label.get_color()
        self.previewcolor.SetBackgroundColour(wxColour(color.get_red(),
        color.get_green(), color.get_blue()))
        box_color.Add(self.previewcolor, 1, wxGROW | wxALL, 5)
        # color change button, opens a new color dialog
        button = wxButton(self, ID_COLOR_CHANGE, _("Change Color"))
        button.SetFocus()
        EVT_BUTTON(self, ID_COLOR_CHANGE, self.OnChangeColor)
        box_color.Add(button, 1, wxEXPAND|wxALL, 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 = wxStaticBox(self, 1011, _("Type"),  style = 0,
	                             name = "type")
        box_type = wxStaticBoxSizer(box_typeStatic, wxVERTICAL)
        sam = []
        for key in label_font_type:
            # dont add truetype
            #if key != 0:
            sam.append(label_font_type[key])
        self.choice_type = wxChoice(self, 40, (80, 50), choices = sam)
        self.choice_type.SetStringSelection(insidetype)
        box_type.Add(self.choice_type,0, wxEXPAND, wxALL, 5)        

        # Offset
        offset= wxStaticBox(self, 1010, _("Offset"), style = 0,
	                    name = "Offset Box",   )
        box_offset = wxStaticBoxSizer(offset, wxVERTICAL)
        umn_label_offset = self.umn_label.get_offset()
        box_offsetX = wxBoxSizer(wxHORIZONTAL)        
        box_offsetX.Add(wxStaticText(self, -1, _("X: ")), 0, wxALL, 2)
        self.text_offsetx = wxSpinCtrl(self, -1, 
                              value=str(umn_label_offset[0]), max=20, min=0,
                              name='offsetX', style=wxSP_ARROW_KEYS)
        box_offsetX.Add(self.text_offsetx, 2, wxALL, 2)
        box_offset.Add(box_offsetX, 0, wxALIGN_RIGHT | wxALL, 2)
        box_offsetY = wxBoxSizer(wxHORIZONTAL)
        box_offsetY.Add(wxStaticText(self, -1, _("Y: ")), 0, wxALL, 2),
        self.text_offsety = wxSpinCtrl(self, -1, 
                              value=str(umn_label_offset[1]), max=100, min=0,
                              name='offsetY', style=wxSP_ARROW_KEYS)
        box_offsetY.Add(self.text_offsety, 2, wxALL, 2)
        box_offset.Add(box_offsetY, 0, wxALIGN_RIGHT | wxALL, 2)
        
        # partials
        umn_partials = self.umn_label.get_partials()
        self.choice_partials = wxRadioBox(self, -1, choices=["True","False"],
                                          label='partials', majorDimension=1,
                                          name='partials check', 
					  size=wxDefaultSize,
	                                  style=wxRA_SPECIFY_ROWS)
        self.choice_partials.SetStringSelection(str(umn_partials))

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

        # buffer
        buffer = wxStaticBox(self, 1010, _("Buffer"), style = 0,
	                     name = "Buffer Box",   )
        box_buffer = wxStaticBoxSizer(buffer, wxVERTICAL)
        umn_buffer= self.umn_label.get_buffer()
        box_buffertext = wxBoxSizer(wxHORIZONTAL)        
        self.text_buffer = wxSpinCtrl(self, -1, 
                              value=str(umn_buffer), max=10, min=0,
                              name='size', style=wxSP_ARROW_KEYS)
        box_buffertext.Add(self.text_buffer, 2, wxALL, 2)
        box_buffer.Add(box_buffertext, 0, wxALIGN_RIGHT | wxALL, 2)

        # minfeaturesize
        minfeaturesize = wxStaticBox(self, 1010, _("Minfeaturesize"),
	                             style = 0, name = "Minfeaturesize Box")
        box_minfeaturesize = wxStaticBoxSizer(minfeaturesize, wxVERTICAL)
        umn_minfeaturesize= self.umn_label.get_minfeaturesize()
        box_minfeaturesizetext = wxBoxSizer(wxHORIZONTAL)        
        self.text_minfeaturesize = wxSpinCtrl(self, -1, 
                              value=str(umn_minfeaturesize), max=10, min=-1,
                              name='minfeaturesize', style=wxSP_ARROW_KEYS)
        box_minfeaturesizetext.Add(self.text_minfeaturesize, 2, wxALL, 2)
        box_minfeaturesize.Add(box_minfeaturesizetext, 0, 
                                             wxALIGN_RIGHT | wxALL, 2)

        # mindistance
        mindistance = wxStaticBox(self, 1010, _("Mindistance"), style = 0,
                                            name = "Mindistance Box",   )
        box_mindistance = wxStaticBoxSizer(mindistance, wxVERTICAL)
        umn_mindistance= self.umn_label.get_mindistance()
        box_mindistancetext = wxBoxSizer(wxHORIZONTAL)        
        self.text_mindistance = wxSpinCtrl(self, -1, 
                              value=str(umn_mindistance), max=10, min=-1,
                              name='mindistance', style=wxSP_ARROW_KEYS)
        box_mindistancetext.Add(self.text_mindistance, 2, wxALL, 2)
        box_mindistance.Add(box_mindistancetext, 0, 
                                             wxALIGN_RIGHT | wxALL, 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 = wxRadioBox(self, -1, choices=possible_choices,
                                          label='Position', majorDimension=1,
                                          name='position check', 
					  size=wxDefaultSize,
	                                  style=wxRA_SPECIFY_ROWS)
        self.choice_position.SetStringSelection(umn_label_position)
  
        #buttons
        box_buttons = wxBoxSizer(wxHORIZONTAL)
        button = wxButton(self, wxID_OK, _("OK"))
        box_buttons.Add(button, 0, wxALL, 5)
        button = wxButton(self, wxID_CANCEL, _("Cancel"))
        box_buttons.Add(button, 0, wxALL, 5)
        #set the button funcitons
        EVT_BUTTON(self, wxID_OK, self.OnOK)
        EVT_BUTTON(self, wxID_CANCEL, self.OnCancel)        
        
        # compose the Dialog
        top = wxBoxSizer(wxVERTICAL)
        
        top1 = wxBoxSizer(wxHORIZONTAL)
        top1.Add(box_labelsize,0, wxEXPAND |wxALL, 5) 
        top1.Add(box_color,0, wxEXPAND |wxALL, 5) 
        top1.Add(box_minfeaturesize,0, wxEXPAND |wxALL, 5) 
        
        top2 = wxBoxSizer(wxHORIZONTAL)
        top2.Add(box_type,0,wxEXPAND |wxALL, 5)
        top2.Add(box_offset,0, wxEXPAND |wxALL, 5)   
        top2.Add(box_mindistance,0, wxEXPAND |wxALL, 5) 
        
        top3 = wxBoxSizer(wxHORIZONTAL)
        top3.Add(self.choice_partials,0, wxEXPAND |wxALL, 5) 
        top3.Add(box_buffer,0, wxEXPAND |wxALL, 5) 
        top3.Add(self.choice_force,0, wxEXPAND |wxALL, 5) 
        
        top.Add(top1, 0, wxEXPAND)
        top.Add(top2, 0, wxEXPAND)
        top.Add(top3, 0, wxEXPAND)
        top.Add(self.choice_position,0, wxEXPAND |wxALL, 5) 
        top.Add(box_buttons, 0, wxALIGN_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() == wxID_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(wxColour(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(wxID_OK)
        else:
            self.EndModal(wxID_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(wxDialog):
    
    def __init__(self, parent, ID, title,
                 pos=wxDefaultPosition, size=wxDefaultSize,
                 style=wxDEFAULT_DIALOG_STYLE):
                     
        # initialize the Dialog
        wxDialog.__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 = wxStaticBox(self, 1011, _("Color"),  style = 0,
	                              name = "color")
        box_color = wxStaticBoxSizer(box_colorStatic, wxVERTICAL)
        # preview box
        self.previewcolor = wxPanel(self, 99, name = 'colorPanel',
	                            style = wxSIMPLE_BORDER | wxCLIP_CHILDREN)
        color = self.umn_scalebar.get_color()
        self.previewcolor.SetBackgroundColour(wxColour(color.get_red(),
        color.get_green(), color.get_blue()))
        box_color.Add(self.previewcolor, 1, wxGROW | wxALL, 5)
        # color change button, opens a new color dialog
        button = wxButton(self, ID_COLOR_CHANGE, _("Change Color"))
        button.SetFocus()
        EVT_BUTTON(self, ID_COLOR_CHANGE, self.OnChangeColor)
        box_color.Add(button, 1, wxEXPAND|wxALL, 5)
        # show the two color chooser horizontal
        colorHor = wxBoxSizer(wxHORIZONTAL)
        colorHor.Add(box_color,0, wxEXPAND |wxALL, 5) 
        
        # imagecolor chooser
        box_imgcolorStatic = wxStaticBox(self, 1011, _("Image Color"), 
	                                 style = 0, name = "imgcolor")
        box_imgcolor = wxStaticBoxSizer(box_imgcolorStatic, wxVERTICAL)
        # preview box
        self.previewimgcolor = wxPanel(self, 99, name = 'colorPanel',
	                               style = wxSIMPLE_BORDER|wxCLIP_CHILDREN)
        color = self.umn_scalebar.get_imagecolor()
        self.previewimgcolor.SetBackgroundColour(wxColour(color.get_red(),
                              color.get_green(), color.get_blue()))
        box_imgcolor.Add(self.previewimgcolor, 1, wxGROW | wxALL, 5)
        # color change button, opens a new color dialog
        button = wxButton(self, ID_IMGCOLOR_CHANGE, _("Change ImageColor"))
        button.SetFocus()
        EVT_BUTTON(self, ID_IMGCOLOR_CHANGE, self.OnChangeImageColor)
        box_imgcolor.Add(button, 1, wxEXPAND|wxALL, 5)
        colorHor.Add(box_imgcolor,0, wxEXPAND |wxALL, 5)
        
        # create the intervals
        intervalsStatic = wxStaticBox(self, 1010, _("Intervals"), style = 0,
	                              name = "Intervals Box",   )
        box_intervals = wxStaticBoxSizer(intervalsStatic, wxVERTICAL)
        umn_scalebar_intervals = self.umn_scalebar.get_intervals()
        self.text_intervals = wxSpinCtrl(self, -1, 
                              value=str(umn_scalebar_intervals), max=100, min=0,
                              name='intervals', style=wxSP_ARROW_KEYS)
        box_intervals.Add(self.text_intervals, 0, wxALIGN_RIGHT | wxALL, 2)
        hori2 = wxBoxSizer(wxHORIZONTAL)
        hori2.Add(box_intervals,0, wxEXPAND |wxALL, 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 = wxRadioBox(self, -1, choices=possible_choices,
              label='Style', majorDimension=1,
              name='style check', size=wxDefaultSize, style=wxRA_SPECIFY_ROWS)
        self.choice_style.SetSelection(umn_scalebar_style)
        hori2.Add(self.choice_style, 1, wxEXPAND|wxALL, 5)
        
        #create size settings
        try:
            insidetxt = self.umn_scalebar.get_size()
        except:
            insidetxt = (0,0)
        # create the Size Box
        staticSize = wxStaticBox(self, -1, _("Size"), style = 0, 
	                         name="sizeBox")
        box_size = wxStaticBoxSizer(staticSize, wxHORIZONTAL)
        
        box_sizepartWidth = wxBoxSizer(wxHORIZONTAL)
        box_sizepartWidth.Add(wxStaticText(self, -1, _("Width: ")), 0, wxALL, 4)
        self.text_width = wxTextCtrl(self, -1, str(insidetxt[0]))
        box_sizepartWidth.Add(self.text_width, 2, wxALL, 4)
        box_size.Add(box_sizepartWidth, 0, wxALIGN_RIGHT | wxALL, 5)
        box_sizepartHeight = wxBoxSizer(wxHORIZONTAL)
        box_sizepartHeight.Add(wxStaticText(self, -1, _("Height: ")), 0,
	                                    wxALL, 4)
        self.text_height = wxTextCtrl(self, -1, str(insidetxt[1]))
        box_sizepartHeight.Add(self.text_height, 2, wxALL, 4)
        box_size.Add(box_sizepartHeight, 0, wxALIGN_RIGHT | wxALL, 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 = wxRadioBox(self, -1, choices=possible_choices,
              label='Status', majorDimension=1,
              name='status check', size=wxDefaultSize, style=wxRA_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 = wxRadioBox(self, -1, choices=possible_choices,
                                      label='Position', majorDimension=1,
                                      name='position check', size=wxDefaultSize,
	                              style=wxRA_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 = wxStaticBox(self, -1, _("Unit Type"),  style = 0,
	                              name = "unittype")
        box_units = wxStaticBoxSizer(box_unitsStatic, wxVERTICAL)
        sam = []
        for key in unit_type:
            sam.append(unit_type[key])
        self.choice_units = wxChoice(self, 40, (80, 50), choices = sam)
        self.choice_units.SetStringSelection(insideunit)
        box_units.Add(self.choice_units,0, wxEXPAND, wxALL, 5)    
        
        # button for label
        labelbutton = wxButton(self, ID_LABEL_CHANGE, _("Change Label"))
        EVT_BUTTON(self, ID_LABEL_CHANGE, self.OnChangeLabel)
        
        #buttons
        box_buttons = wxBoxSizer(wxHORIZONTAL)
        button = wxButton(self, wxID_OK, _("OK"))
        box_buttons.Add(button, 0, wxALL, 5)
        button = wxButton(self, wxID_CANCEL, _("Cancel"))
        button.SetFocus()
        box_buttons.Add(button, 0, wxALL, 5)
        #set the button funcitons
        EVT_BUTTON(self, wxID_OK, self.OnOK)
        EVT_BUTTON(self, wxID_CANCEL, self.OnCancel)      
      
        # compose the dialog
        top = wxBoxSizer(wxVERTICAL)
        top.Add(colorHor,0, wxEXPAND |wxALL, 5)
        top.Add(hori2, 1, wxEXPAND|wxALL, 5)
        top.Add(box_size, 1, wxEXPAND|wxALL, 5)
        top.Add(self.choice_status,0, wxEXPAND |wxALL, 5) 
        top.Add(self.choice_position,0, wxEXPAND |wxALL, 5) 
        top.Add(box_units, 1, wxEXPAND|wxALL, 5)
        top.Add(labelbutton, 0, wxEXPAND|wxALL, 5)
        top.Add(box_buttons, 0, wxALIGN_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=wxSize(350, 200),
                 style = wxDEFAULT_DIALOG_STYLE
                 )
        dialog.CenterOnScreen()
        if dialog.ShowModal() == wxID_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() == wxID_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(wxColour(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() == wxID_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(wxColour(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(wxID_OK)
        else:
            self.EndModal(wxID_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(wxPyGridTableBase):
    """
    creates a custum Grid.
    
    copied from the wx demo.
    """
    def __init__(self, data):
        wxPyGridTableBase.__init__(self)

        self.colLabels = ['ID', 'Description']
        self.dataTypes = [wxGRID_VALUE_STRING,
                          wxGRID_VALUE_STRING
                          ]
        
        if data:
            self.data = data
        else:
            self.data = [["",""]]    #--------------------------------------------------
    # required methods for the wxPyGridTableBase 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 = wxGridTableMessage(self,                             # The table
                                     wxGRIDTABLE_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(wxGrid):
    def __init__(self, parent, data):
        wxGrid.__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)
        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(wxDialog):
    
    def __init__(self, parent, ID, title,
                 pos=wxDefaultPosition, size=wxDefaultSize,
                 style=wxDEFAULT_DIALOG_STYLE):
                     
        # initialize the Dialog
        wxDialog.__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 = wxBoxSizer(wxHORIZONTAL)
        button = wxButton(self, wxID_OK, _("OK"))
        box_buttons.Add(button, 0, wxALL, 5)
        button = wxButton(self, wxID_CANCEL, _("Cancel"))
        button.SetFocus()
        box_buttons.Add(button, 0, wxALL, 5)
        #set the button funcitons
        EVT_BUTTON(self, wxID_OK, self.OnOK)
        EVT_BUTTON(self, wxID_CANCEL, self.OnCancel)      
        
        # compose the dialog
        top = wxBoxSizer(wxVERTICAL)
        top.Add(self.grid, 1, wxGROW|wxALL, 5)
        top.Add(box_buttons, 0, wxALIGN_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(wxID_OK)
        else:
            self.EndModal(wxID_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=wxSize(450, 250),
                          style = wxDEFAULT_DIALOG_STYLE)
    win.CenterOnScreen()
    val = win.ShowModal()    
    

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

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

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

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

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

def legendsettings(context):
    win = Legend_Dialog(context.mainwindow, -1, "Legend Settings",
                        size=wxSize(350, 200),
                        style = wxDEFAULT_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 aktive 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")


