# 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: 1.35 $"

import os.path

from Thuban import _

from wxPython.wx import *
from wxPython.grid import *

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.common import ThubanBeginBusyCursor, ThubanEndBusyCursor

wx_value_type_map = {FIELDTYPE_INT: wxGRID_VALUE_NUMBER,
                     FIELDTYPE_DOUBLE: wxGRID_VALUE_FLOAT,
                     FIELDTYPE_STRING: wxGRID_VALUE_STRING}

ROW_SELECTED = "ROW_SELECTED"

QUERY_KEY = 'S'

class DataTable(wxPyGridTableBase):

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

    def __init__(self, table = None):
        wxPyGridTableBase.__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):
        record = self.table.ReadRowAsDict(row, row_is_ordinal = 1)
        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(wxPyGridCellRenderer):

    """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):
        wxPyGridCellRenderer.__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(wxSOLID)
            dc.SetBrush(wxBrush(wxColour(192, 192, 192), wxSOLID))
            dc.SetPen(wxTRANSPARENT_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(wxGrid, 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):
        wxGrid.__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(wxGrid.wxGridSelectRows)

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

        # Replace the normal renderers with our own versions which
        # render NULL/None values specially
        self.RegisterDataType(wxGRID_VALUE_STRING,
                              NullRenderer(wxGridCellStringRenderer()), None)
        self.RegisterDataType(wxGRID_VALUE_NUMBER,
                              NullRenderer(wxGridCellNumberRenderer()), None)
        self.RegisterDataType(wxGRID_VALUE_FLOAT,
                              NullRenderer(wxGridCellFloatRenderer()), None)

        EVT_WINDOW_DESTROY(self, 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 = wxPanel(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 = wxComboBox(self.panel, -1, style=wxCB_READONLY)
        self.choice_comp = wxChoice(self.panel, -1, 
                              choices=["<", "<=", "==", "!=", ">=", ">"])
        self.combo_value = wxComboBox(self.panel, ID_COMBOVALUE)
        self.choice_action = wxChoice(self.panel, -1, 
                                choices=[_("Replace Selection"), 
                                        _("Refine Selection"), 
                                        _("Add to Selection")])

        button_query = wxButton(self.panel, ID_QUERY, _("Query"))
        button_export = wxButton(self.panel, ID_EXPORT, _("Export"))
        button_exportSel = wxButton(self.panel, ID_EXPORTSEL, _("Export Selection"))
        button_close = wxButton(self.panel, wxID_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 = wxBoxSizer(wxVERTICAL)

        sizer = wxStaticBoxSizer(wxStaticBox(self.panel, -1, 
                                  _("Selection")),
                                  wxHORIZONTAL)
        sizer.Add(self.combo_fields, 1, wxEXPAND|wxALL, 4)
        sizer.Add(self.choice_comp, 0, wxALL, 4)
        sizer.Add(self.combo_value, 1, wxEXPAND|wxALL, 4)
        sizer.Add(self.choice_action, 0, wxALL, 4)
        sizer.Add(button_query, 0, wxALL | wxALIGN_CENTER_VERTICAL, 4)
        sizer.Add( (40, 20), 0, wxALL, 4)

        topBox.Add(sizer, 0, wxEXPAND|wxALL, 4)
        topBox.Add(self.grid, 1, wxEXPAND|wxALL, 0)

        sizer = wxBoxSizer(wxHORIZONTAL)
        sizer.Add(button_export, 0, wxALL, 4)
        sizer.Add(button_exportSel, 0, wxALL, 4)
        sizer.Add( (60, 20), 1, wxALL|wxEXPAND, 4)
        sizer.Add(button_close, 0, wxALL|wxALIGN_RIGHT, 4)
        topBox.Add(sizer, 0, wxALL | wxEXPAND, 4)

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

        panelSizer = wxBoxSizer(wxVERTICAL)
        panelSizer.Add(self.panel, 1, wxEXPAND, 0)
        self.SetAutoLayout(True)
        self.SetSizer(panelSizer)
        panelSizer.Fit(self)
        panelSizer.SetSizeHints(self)

        self.grid.SetFocus()

        EVT_BUTTON(self, ID_QUERY, self.OnQuery)
        EVT_BUTTON(self, ID_EXPORT, self.OnExport)
        EVT_BUTTON(self, ID_EXPORTSEL, self.OnExportSel)
        EVT_BUTTON(self, wxID_CLOSE, self.OnClose)
        EVT_KEY_DOWN(self.grid, self.OnKeyDown)

        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 = wxFileDialog(self, _("Export Table To"), ".", "",
                           _("DBF Files (*.dbf)|*.dbf|") +
                           _("CSV Files (*.csv)|*.csv|") +
                           _("All Files (*.*)|*.*"),
                           wxSAVE|wxOVERWRITE_PROMPT)
        if dlg.ShowModal() == wxID_OK:
            filename = 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 = wxMessageDialog(None, "Unsupported format: %s" % type,
                                      "Table Export", wxOK|wxICON_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()

