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

__version__ = "$Revision: 2817 $"

import os.path

from Thuban import _

import wx
from wx import grid

from Thuban.Lib.connector import Publisher
from Thuban.Model.table import FIELDTYPE_INT, FIELDTYPE_DOUBLE, \
     FIELDTYPE_STRING, table_to_dbf, table_to_csv
from dialogs import ThubanFrame

from messages import SHAPES_SELECTED, SESSION_REPLACED
from Thuban.Model.messages import TABLE_REMOVED, MAP_LAYERS_REMOVED
from Thuban.UI import internal_from_wxstring
from Thuban.UI.common import ThubanBeginBusyCursor, ThubanEndBusyCursor

wx_value_type_map = {FIELDTYPE_INT: grid.GRID_VALUE_NUMBER,
                     FIELDTYPE_DOUBLE: grid.GRID_VALUE_FLOAT,
                     FIELDTYPE_STRING: grid.GRID_VALUE_STRING}

ROW_SELECTED = "ROW_SELECTED"

QUERY_KEY = 'S'

class DataTable(grid.PyGridTableBase):

    """Wrapper around a Thuban table object suitable for a wxGrid"""

    def __init__(self, table = None):
        grid.PyGridTableBase.__init__(self)
        self.num_cols = 0
        self.num_rows = 0
        self.columns = []
        self.table = None
        self.SetTable(table)

    def SetTable(self, table):
        self.table = table
        self.num_cols = table.NumColumns()
        self.num_rows = table.NumRows()

        self.columns = []
        for i in range(self.num_cols):
            col = table.Column(i)
            self.columns.append((col.name, wx_value_type_map[col.type]))

    #
    # required methods for the wxPyGridTableBase interface
    #

    def GetNumberRows(self):
        return self.num_rows

    def GetNumberCols(self):
        return self.num_cols

    def IsEmptyCell(self, row, col):
        return 0

    # 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:
            record = self.table.ReadRowAsDict(row, row_is_ordinal = 1)
        except UnicodeError:
            record = dict()
            for (key, val) in self.table.ReadRowAsDict(row, \
                              row_is_ordinal = 1).items():
                if isinstance(val, str):
                    record[key] = val.decode('iso-8859-1')
                else:
                    record[key] = val
        return record[self.columns[col][0]]

    def SetValue(self, row, col, value):
        pass

    #
    # Some optional methods
    #

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

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

    # 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):
        # perhaps we should allow conversion int->double?
        return self.GetTypeName(row, col) == typeName

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


    #
    def RowIdToOrdinal(self, rowid):
        """Return the ordinal of the row given by its id"""
        return self.table.RowIdToOrdinal(rowid)

    def RowOrdinalToId(self, ordinal):
        """Return the id of the row given by its ordinal"""
        return self.table.RowOrdinalToId(ordinal)


class NullRenderer(grid.PyGridCellRenderer):

    """Renderer that draws NULL as a gray rectangle

    Other values are delegated to a normal renderer which is given as
    the parameter to the constructor.
    """

    def __init__(self, non_null_renderer):
        grid.PyGridCellRenderer.__init__(self)
        self.non_null_renderer = non_null_renderer

    def Draw(self, grid, attr, dc, rect, row, col, isSelected):
        value = grid.table.GetValue(row, col)
        if value is None:
            dc.SetBackgroundMode(wx.SOLID)
            dc.SetBrush(wx.Brush(wx.Colour(192, 192, 192), wx.SOLID))
            dc.SetPen(wx.TRANSPARENT_PEN)
            dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)
        else:
            self.non_null_renderer.Draw(grid, attr, dc, rect, row, col,
                                        isSelected)

    def GetBestSize(self, grid, attr, dc, row, col):
        self.non_null_renderer.GetBestSize(grid, attr, dc, row, col)

    def Clone(self):
        return NullRenderer(self.non_null_renderer)


class TableGrid(grid.Grid, Publisher):

    """A grid view for a Thuban table

    When rows are selected by the user the table issues ROW_SELECTED
    messages. wx sends selection events even when the selection is
    manipulated by code (instead of by the user) which usually lead to
    ROW_SELECTED messages being sent in turn. Therefore sending messages
    can be switched on and off with the allow_messages and
    disallow_messages methods.
    """

    def __init__(self, parent, table = None):
        grid.Grid.__init__(self, parent, -1)

        self.allow_messages_count = 0

        # keep track of which rows are selected.
        self.rows = {}

        self.table = DataTable(table)

        # 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 its Destroy
        # method later.
        self.SetTable(self.table, True)

        #self.SetMargins(0,0)

        # AutoSizeColumns would allow us to make the grid have optimal
        # column widths automatically but it would cause a traversal of
        # the entire table which for large .dbf files can take a very
        # long time.
        #self.AutoSizeColumns(False)

        self.SetSelectionMode(grid.Grid.wxGridSelectRows)

        self.ToggleEventListeners(True)
        self.Bind(grid.EVT_GRID_RANGE_SELECT, self.OnRangeSelect)
        self.Bind(grid.EVT_GRID_SELECT_CELL, self.OnSelectCell)

        # Replace the normal renderers with our own versions which
        # render NULL/None values specially
        self.RegisterDataType(grid.GRID_VALUE_STRING,
                              NullRenderer(grid.GridCellStringRenderer()), None)
        self.RegisterDataType(grid.GRID_VALUE_NUMBER,
                              NullRenderer(grid.GridCellNumberRenderer()), None)
        self.RegisterDataType(grid.GRID_VALUE_FLOAT,
                              NullRenderer(grid.GridCellFloatRenderer()), None)

        self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)

    def OnDestroy(self, event):
        Publisher.Destroy(self)

    def SetTableObject(self, table):
        self.table.SetTable(table)

    def OnRangeSelect(self, event):
        to_id = self.table.RowOrdinalToId
        if self.handleSelectEvents:
            self.rows = dict([(to_id(i), 0) for i in self.GetSelectedRows()])

            # if we're selecting we need to include the selected range and
            # make sure that the current row is also included, which may
            # not be the case if you just click on a single row!
            if event.Selecting():
                for i in range(event.GetTopRow(), event.GetBottomRow() + 1):
                    self.rows[to_id(i)] = 0
                self.rows[to_id(event.GetTopLeftCoords().GetRow())] = 0

            self.issue(ROW_SELECTED, self.rows.keys())

        event.Skip()

    def OnSelectCell(self, event):
        to_id = self.table.RowOrdinalToId
        if self.handleSelectEvents:
            self.issue(ROW_SELECTED,
                       [to_id(i) for i in self.GetSelectedRows()])
        event.Skip()

    def ToggleEventListeners(self, on):
        self.handleSelectEvents = on

    def GetNumberSelected(self):
        return len(self.rows)

    def disallow_messages(self):
        """Disallow messages to be send.

        This method only increases a counter so that calls to
        disallow_messages and allow_messages can be nested. Only the
        outermost calls will actually switch message sending on and off.
        """
        self.allow_messages_count += 1

    def allow_messages(self):
        """Allow messages to be send.

        This method only decreases a counter so that calls to
        disallow_messages and allow_messages can be nested. Only the
        outermost calls will actually switch message sending on and off.
        """
        self.allow_messages_count -= 1

    def issue(self, *args):
        """Issue a message unless disallowed.

        See the allow_messages and disallow_messages methods.
        """
        if self.allow_messages_count == 0:
            Publisher.issue(self, *args)

    def SelectRowById(self, rowid, do_select):
        """Select row with the id rowid"""
        self.SelectRow(self.table.RowIdToOrdinal(rowid), do_select)


class LayerTableGrid(TableGrid):

    """Table grid for the layer tables.

    The LayerTableGrid is basically the same as a TableGrid but it's
    selection is usually coupled to the selected object in the map.
    """

    def select_shapes(self, layer, shapes):
        """Select the row corresponding to the specified shape and layer

        If layer is not the layer the table is associated with do
        nothing. If shape or layer is None also do nothing.
        """
        if layer is not None \
            and layer.ShapeStore().Table() is self.table.table:

            self.disallow_messages()
            try:
                self.ClearSelection()
                if len(shapes) > 0:
                    # keep track of the lowest id so we can make it the
                    # first visible item
                    first = -1

                    to_ordinal = self.table.RowIdToOrdinal
                    for shape in shapes:
                        row = to_ordinal(shape)
                        self.SelectRow(row, True)
                        if row < first:
                            first = row

                    self.SetGridCursor(first, 0)
                    self.MakeCellVisible(first, 0)
            finally:
                self.allow_messages()


class TableFrame(ThubanFrame):

    """Frame that displays a Thuban table in a grid view"""

    def __init__(self, parent, name, title, table):
        ThubanFrame.__init__(self, parent, name, title)
        self.panel = wx.Panel(self, -1)

        self.table = table
        self.grid = self.make_grid(self.table)
        self.app = self.parent.application
        self.app.Subscribe(SESSION_REPLACED, self.close_on_session_replaced)
        self.session = self.app.Session()
        self.session.Subscribe(TABLE_REMOVED, self.close_on_table_removed)

    def OnDestroy(self, event):
        """Extend inherited method to unsubscribe messages"""
        self.app.Unsubscribe(SESSION_REPLACED, self.close_on_session_replaced)
        self.session.Unsubscribe(TABLE_REMOVED, self.close_on_table_removed)
        ThubanFrame.OnDestroy(self, event)

    def make_grid(self, table):
        """Return the table grid to use in the frame.

        The default implementation returns a TableGrid instance.
        Override in derived classes to use different grid classes.
        """
        return TableGrid(self, table)

    def close_on_session_replaced(self, *args):
        """Subscriber for the SESSION_REPLACED messages.

        The table frame is tied to a session so close the window when
        the session changes.
        """
        self.Close()

    def close_on_table_removed(self, table):
        """Subscriber for the TABLE_REMOVED messages.

        The table frame is tied to a particular table so close the
        window when the table is removed.
        """
        if table is self.table:
            self.Close()


ID_QUERY = 4001
ID_EXPORT = 4002
ID_COMBOVALUE = 4003
ID_EXPORTSEL = 4004

class QueryTableFrame(TableFrame):

    """Frame that displays a table in a grid view and offers user actions
    selection and export

    A QueryTableFrame is TableFrame whose selection is connected to the
    selected object in a map.
    """

    def __init__(self, parent, name, title, table):
        TableFrame.__init__(self, parent, name, title, table)

        self.combo_fields = wx.ComboBox(self.panel, -1, style=wx.CB_READONLY)
        self.choice_comp = wx.Choice(self.panel, -1,
                              choices=["<", "<=", "==", "!=", ">=", ">"])
        self.combo_value = wx.ComboBox(self.panel, ID_COMBOVALUE)
        self.choice_action = wx.Choice(self.panel, -1,
                                choices=[_("Replace Selection"),
                                        _("Refine Selection"),
                                        _("Add to Selection")])

        button_query = wx.Button(self.panel, ID_QUERY, _("Query"))
        button_export = wx.Button(self.panel, ID_EXPORT, _("Export"))
        button_exportSel = wx.Button(self.panel, ID_EXPORTSEL, _("Export Selection"))
        button_close = wx.Button(self.panel, wx.ID_CLOSE, _("Close"))

        self.CreateStatusBar()

        self.grid.SetSize((400, 200))

        self.combo_value.Append("")
        for i in range(table.NumColumns()):
            name = table.Column(i).name
            self.combo_fields.Append(name)
            self.combo_value.Append(name)

        # assume at least one field?
        self.combo_fields.SetSelection(0)
        self.combo_value.SetSelection(0)
        self.choice_action.SetSelection(0)
        self.choice_comp.SetSelection(0)

        self.grid.Reparent(self.panel)

        self.UpdateStatusText()

        topBox = wx.BoxSizer(wx.VERTICAL)

        sizer = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1,
                                  _("Selection")),
                                  wx.HORIZONTAL)
        sizer.Add(self.combo_fields, 1, wx.EXPAND|wx.ALL, 4)
        sizer.Add(self.choice_comp, 0, wx.ALL, 4)
        sizer.Add(self.combo_value, 1, wx.EXPAND|wx.ALL, 4)
        sizer.Add(self.choice_action, 0, wx.ALL, 4)
        sizer.Add(button_query, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 4)
        sizer.Add( (40, 20), 0, wx.ALL, 4)

        topBox.Add(sizer, 0, wx.EXPAND|wx.ALL, 4)
        topBox.Add(self.grid, 1, wx.EXPAND|wx.ALL, 0)

        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(button_export, 0, wx.ALL, 4)
        sizer.Add(button_exportSel, 0, wx.ALL, 4)
        sizer.Add( (60, 20), 1, wx.ALL|wx.EXPAND, 4)
        sizer.Add(button_close, 0, wx.ALL|wx.ALIGN_RIGHT, 4)
        topBox.Add(sizer, 0, wx.ALL | wx.EXPAND, 4)

        self.panel.SetAutoLayout(True)
        self.panel.SetSizer(topBox)
        topBox.Fit(self.panel)
        topBox.SetSizeHints(self.panel)

        panelSizer = wx.BoxSizer(wx.VERTICAL)
        panelSizer.Add(self.panel, 1, wx.EXPAND, 0)
        self.SetAutoLayout(True)
        self.SetSizer(panelSizer)
        panelSizer.Fit(self)
        panelSizer.SetSizeHints(self)

        self.grid.SetFocus()

        self.Bind(wx.EVT_BUTTON, self.OnQuery, id=ID_QUERY)
        self.Bind(wx.EVT_BUTTON, self.OnExport, id=ID_EXPORT)
        self.Bind(wx.EVT_BUTTON, self.OnExportSel, id=ID_EXPORTSEL)
        self.Bind(wx.EVT_BUTTON, self.OnClose, id=wx.ID_CLOSE)
        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown, self.grid)

        self.grid.Subscribe(ROW_SELECTED, self.UpdateStatusText)

    def UpdateStatusText(self, rows=None):
        self.SetStatusText(_("%i rows (%i selected), %i columns")
            % (self.grid.GetNumberRows(),
               self.grid.GetNumberSelected(),
               self.grid.GetNumberCols()))

    def OnKeyDown(self, event):
        """Catch query key from grid"""
        if event.AltDown() and event.GetKeyCode() == ord(QUERY_KEY):
            self.combo_fields.SetFocus()
            self.combo_fields.refocus = True
        else:
            event.Skip()

    def OnQuery(self, event):
        ThubanBeginBusyCursor()
        try:

            text = self.combo_value.GetValue()
            if self.combo_value.GetSelection() < 1 \
                or self.combo_value.FindString(text) == -1:
                value = text
            else:
                value = self.table.Column(text)

            ids = self.table.SimpleQuery(
                    self.table.Column(self.combo_fields.GetStringSelection()),
                    self.choice_comp.GetStringSelection(),
                    value)

            choice = self.choice_action.GetSelection()

            #
            # what used to be nice code got became a bit ugly because
            # each time we select a row a message is sent to the grid
            # which we are listening for and then we send further 
            # messages. 
            #
            # now, we disable those listeners select everything but
            # the first item, reenable the listeners, and select
            # the first element, which causes everything to be
            # updated properly.
            #
            if ids:
                self.grid.ToggleEventListeners(False)

            if choice == 0:
                # Replace Selection
                self.grid.ClearSelection()
            elif choice == 1:
                # Refine Selection
                sel = self.get_selected()
                self.grid.ClearSelection()
                ids = filter(sel.has_key, ids)
            elif choice == 2:
                # Add to Selection
                pass

            #
            # select the rows (all but the first)
            # 
            firsttime = True
            for id in ids:
                if firsttime:
                    firsttime = False
                else:
                    self.grid.SelectRowById(id, True)

            self.grid.ToggleEventListeners(True)

            #
            # select the first row
            #
            if ids:
                self.grid.SelectRowById(ids[0], True)

        finally:
            ThubanEndBusyCursor()

    def doExport(self, onlySelected):

        dlg = wx.FileDialog(self, _("Export Table To"), ".", "",
                           _("DBF Files (*.dbf)|*.dbf|") +
                           _("CSV Files (*.csv)|*.csv|") +
                           _("All Files (*.*)|*.*"),
                           wx.SAVE|wx.OVERWRITE_PROMPT)
        if dlg.ShowModal() == wx.ID_OK:
            filename = internal_from_wxstring(dlg.GetPath())
            type = os.path.basename(filename).split('.')[-1:][0]
            dlg.Destroy()

            if onlySelected:
                records = self.grid.GetSelectedRows()
            else:
                records = None

            if type.upper() == "DBF":
                table_to_dbf(self.table, filename, records)
            elif type.upper() == 'CSV':
                table_to_csv(self.table, filename, records)
            else:
                dlg = wx.MessageDialog(None, "Unsupported format: %s" % type,
                                      "Table Export", wx.OK|wx.ICON_WARNING)
                dlg.ShowModal()
                dlg.Destroy()
        else:
            dlg.Destroy()

    def OnExport(self, event):
        self.doExport(False)

    def OnExportSel(self, event):
        self.doExport(True)

    def OnClose(self, event):
        TableFrame.OnClose(self, event)

    def get_selected(self):
        """Return a dictionary of the selected rows.

        The dictionary has the indexes as keys."""
        to_id = self.table.RowOrdinalToId
        return dict([(to_id(i), 0) for i in self.grid.GetSelectedRows()])


class LayerTableFrame(QueryTableFrame):

    """Frame that displays a layer table in a grid view

    A LayerTableFrame is a QueryTableFrame whose selection is connected to the
    selected object in a map.
    """

    def __init__(self, parent, name, title, layer, table):
        QueryTableFrame.__init__(self, parent, name, title, table)
        self.layer = layer
        self.grid.Subscribe(ROW_SELECTED, self.rows_selected)
        self.parent.Subscribe(SHAPES_SELECTED, self.select_shapes)
        self.map = self.parent.Map()
        self.map.Subscribe(MAP_LAYERS_REMOVED, self.map_layers_removed)

        # if there is already a selection present, update the grid
        # accordingly
        sel = self.get_selected().keys()
        for i in sel:
            self.grid.SelectRowById(i, True)

    def OnDestroy(self, event):
        """Extend inherited method to unsubscribe messages"""
        # There's no need to unsubscribe from self.grid's messages
        # because it will get a DESTROY event too (since destroying the
        # frame basically means that all child windows are also
        # destroyed) and this it will clear all subscriptions
        # automatically.  It may even have been destroyed already (this
        # does happen on w2000 for instance) so calling any of its
        # methods here would be an error.
        self.parent.Unsubscribe(SHAPES_SELECTED, self.select_shapes)
        self.map.Unsubscribe(MAP_LAYERS_REMOVED, self.map_layers_removed)
        QueryTableFrame.OnDestroy(self, event)

    def make_grid(self, table):
        """Override the derived method to return a LayerTableGrid.
        """
        return LayerTableGrid(self, table)

    def get_selected(self):
        """Override the derived method to return a dictionary of the selected
        rows.
        """
        return dict([(i, 0) for i in self.parent.SelectedShapes()])

    def select_shapes(self, layer, shapes):
        """Subscribed to the SHAPES_SELECTED message.

        If shapes contains exactly one shape id, select that shape in
        the grid. Otherwise deselect all.
        """
        self.grid.select_shapes(layer, shapes)

    def rows_selected(self, rows):
        """Return the selected rows of the layer as they are returned
        by Layer.SelectShapes().
        """
        if self.layer is not None:
            self.parent.SelectShapes(self.layer, rows)

    def map_layers_removed(self, *args):
        """Receiver for the map's MAP_LAYERS_REMOVED message

        Close the dialog if the layer whose table we're showing is not
        in the map anymore.
        """
        if self.layer not in self.map.Layers():
            self.Close()

