# Copyright (C) 2005, 2008 by Intevation GmbH
# Authors:
# Jan-Oliver Wagner <jan@intevation.de> (2005)
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with Thuban for details.

"""
Extend Thuban with a routine to export a layer
as a Shapefile.
"""

__version__ = '$Revision: 2817 $'
# $Source$
# $Id: export_shapefile.py 2817 2008-01-27 00:01:32Z bernhard $

from wx import FileDialog, OPEN, OVERWRITE_PROMPT, ID_OK, \
     ProgressDialog

from Thuban.Model.data import SHAPETYPE_POLYGON, SHAPETYPE_ARC, \
                              SHAPETYPE_POINT
from Thuban.Model.table import table_to_dbf
from Thuban.UI import internal_from_wxstring
from Thuban.UI.command import registry, Command
from Thuban.UI.mainwindow import main_menu
from Thuban import _

import shapelib

def ExportLayerAsShapefile(context):
    """Request filename from user, 
    and create the Shapefile(s) .shp, .dbf and .shx.

    context -- The Thuban context.
    """
    # First, find the current layer
    layer = context.mainwindow.canvas.SelectedLayer()
    if layer is None:
       context.mainwindow.RunMessageBox(_('Export Shapefile'),
           _('No layer selected'))
       return

    # Second, get the basefilename for the shapefile.
    dlg = FileDialog(context.mainwindow,
                       _('Export Shapefile'), '.', '',
                       _('Shapefile  Files (*.shp)|*.shp|'),
                       OPEN|OVERWRITE_PROMPT)
    if dlg.ShowModal() == ID_OK:
        filename = internal_from_wxstring(dlg.GetPath()[:-4])
        dlg.Destroy()
    else:
        return

    # Third, create the dbf file of the new Shapefile
    dbf_filename = filename + '.dbf'
    if hasattr(layer, "ShapeStore"):
        table = layer.ShapeStore().Table()
        table_to_dbf(table, dbf_filename)

    # Fourth, prepare the shp file of the new Shapefile
    shp_filename = filename + '.shp'
    shapetypes = { SHAPETYPE_POLYGON: shapelib.SHPT_POLYGON,
        SHAPETYPE_ARC: shapelib.SHPT_ARC,
        SHAPETYPE_POINT: shapelib.SHPT_POINT}
    shp = shapelib.create(shp_filename, shapetypes[layer.ShapeType()])

    # Now go through all shapes and store them to the file
    dlg= ProgressDialog(_("Export Shapefile"),
                          _("Storing shapes ..."),
                          layer.ShapeStore().NumShapes(),
                          None)

    cnt = 0
    step =  int(layer.ShapeStore().NumShapes() / 100.0)
    if step == 0: step = 1

    for s in layer.ShapeStore().AllShapes():
        i = s.ShapeID()
        print s.Points()
        obj = shapelib.SHPObject(shapetypes[layer.ShapeType()], i, s.Points())
        shp.write_object(i, obj)
        if cnt % step == 0:
            dlg.Update(cnt)
        cnt = cnt + 1

    del shp
    dlg.Destroy()


# register the new command
registry.Add(Command('ExportShapefile',  _("(experimental) ")+ _('Export Layer as Shapefile ...'),
                     ExportLayerAsShapefile,
                     helptext = _('Export the active layer as a Shapefile')))

# find the entension menu (create it anew if not found)
extensions_menu = main_menu.FindOrInsertMenu('extensions',
                                               _('E&xtensions'))

# finally add the new entry to the menu
extensions_menu.InsertItem('ExportShapefile')
