# Copyright (c) 2004 by Intevation GmbH
# Authors:
# Markus Rechtien <markus@intevation.de> (2004)
# Bernhard Herzog <bh@intevation.de> (2004)
# Bernhard Reiter <bernhard@intevation.de> (2004)
# Jan-Oliver Wagner <jan@intevation.de> (2004)
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with Thuban for details.

__version__ = "$Revision: 2818 $"
# $Source$
# $Id: svgsaver.py 2818 2008-01-27 23:41:08Z bernhard $


"""
Classes to write a session in SVG format
"""


# Needed wx-toolkit classes
from wx import FileDialog, SAVE, OVERWRITE_PROMPT, ID_OK, \
        OK, ICON_HAND

# We need os.path
import os

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

# Import SVG related classes
from svgmapwriter import VirtualDC, SVGRenderer, SVGMapWriterError


def write_to_svg(context):
    '''Export data depending on the set properties.

    This is the main export funcation.
    '''
    canvas = context.mainwindow.canvas
    file = None
    map = canvas.Map()
    
    if hasattr(canvas, "export_path"):
        export_path = canvas.export_path
    else:
        export_path="."
    # Get the file the session shall be written to
    dlg = FileDialog(canvas, _("Write SVG"), export_path, "", 
            "Scalable Vector Graphics (*.svg)|*.svg", 
            SAVE|OVERWRITE_PROMPT)
    
    response = dlg.ShowModal()
    if response == ID_OK:
        file = internal_from_wxstring(dlg.GetPath())
    else: # Do nothing if choice was interrupted.
        return 0
        
    # If the user selected a file
    if file and map is not None:
        canvas.export_path = os.path.dirname(file)
        # Initialize some dimensions and calculate the map bounds
        width, height = canvas.GetSizeTuple()
        llx, lly = canvas.win_to_proj(0, height)
        urx, ury = canvas.win_to_proj(width, 0)
        mapwidth, mapheight = ((urx - llx), (ury - lly))
        mapregion = (llx, lly, mapwidth, mapheight)
        
        # Get all selected layers and shapes that should be written as SVG
        selected_layer = canvas.selection.SelectedLayer()
        selected_shapes = canvas.selection.SelectedShapes()
        try:
            dc = VirtualDC(file, (mapwidth, mapheight, ))
            dc.BeginExport()
            # map scale offset region
            renderer = SVGRenderer(dc, map, 1.0, (0 - min(llx, urx),
                    0 + max(lly, ury)), mapregion)
            # Render the map
            renderer.RenderMap(selected_layer, selected_shapes)
            dc.EndExport()
        except SVGMapWriterError, inst:
            context.mainwindow.RunMessageBox(_("Error: SVG not written!"),
                text=_("Could not write SVG because: ")+ str(inst),
                flags= OK | ICON_HAND)
            # delete partly writting file
            os.remove(file)



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

# The instance of the main menu of the Thuban application
# See Thuban/UI/menu.py for the API of the Menu class
from Thuban.UI.mainwindow import main_menu

# create a new command and register it
registry.Add(Command('write_to_svg', _('Write SVG Map'), write_to_svg,
                     helptext = _('Export the map into an SVG file')))

# find the menu we want to be in (create it anew if not found)
menu = main_menu.FindOrInsertMenu('extensions', _('E&xtensions'))

# finally bind the new command with an entry in the extensions menu
menu.InsertItem('write_to_svg')
