# 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.


"""Common Thuban specific control widgets"""

__version__ = "$Revision: 1.8 $"

from wxPython.wx import wxListCtrl, wxLC_REPORT, wxLIST_AUTOSIZE_USEHEADER, \
     EVT_LIST_ITEM_SELECTED
from wxPython.grid import wxPyGridTableBase, wxGrid, wxGRID_VALUE_STRING, \
     wxGridTableMessage, wxGRIDTABLE_NOTIFY_ROWS_APPENDED, \
     wxGRIDTABLE_NOTIFY_ROWS_DELETED, wxGRIDTABLE_REQUEST_VIEW_GET_VALUES

from Thuban import _

# FIXME: the wx_value_type_map should be moved from tableview to a
# separate module
from tableview import wx_value_type_map



class RecordListCtrl(wxListCtrl):

    """List Control showing a single record from a thuban table"""

    def __init__(self, parent, id):
        wxListCtrl.__init__(self, parent, id, style = wxLC_REPORT)

        self.InsertColumn(0, _("Field"))
        self.SetColumnWidth(0, 200)
        self.InsertColumn(1, _("Value"))
        self.SetColumnWidth(1, 100)

        # vaues maps row numbers to the corresponding python values
        self.values = {}

    def fill_list(self, table, shape):
        """Fill self with the contents shape's record from table"""
        self.DeleteAllItems()
        values = {}

        if shape is not None:
            names = []
            for col in table.Columns():
                names.append(col.name)
            record = table.ReadRowAsDict(shape)

            for i in range(len(names)):
                name = names[i]
                value = record[name]
                self.InsertStringItem(i, name)
                self.SetStringItem(i, 1, str(value))
                values[i] = value

        self.values = values

class SelectableRecordListCtrl(RecordListCtrl):

    def __init__(self, parent, id):
        RecordListCtrl.__init__(self, parent, id)

        # selected is the index of the selected record or -1 if none is
        # selected
        self.selected = -1
        EVT_LIST_ITEM_SELECTED(self, self.GetId(), self.OnItemSelected)

    def OnItemSelected(self, event):
        """Event handler. Update the selected instvar"""
        self.selected = event.m_itemIndex

    def GetValue(self):
        """Return the currently selected value. None if no value is selected"""
        if self.selected >= 0:
            return self.values[self.selected]
        else:
            return None


class RecordTable(wxPyGridTableBase):

    """Wrapper that makes a Thuban table record look like a table for a
       wxGrid
    """

    def __init__(self, table = None, record = None):
        wxPyGridTableBase.__init__(self)
        self.num_cols = 1
        self.num_rows = 0
        self.table = None
        self.record_index = record
        self.record = None
        self.SetTable(table, record)

    def SetTable(self, table, record_index):
        old_num_rows = self.num_rows
        if record_index is not None:
            self.table = table
            self.record_index = record_index
            self.record = table.ReadRowAsDict(record_index)

            # we have one row for each field in the table
            self.num_rows = table.NumColumns()

            # extract the field types and names of the row we're showing.
            self.rows = []
            for i in range(self.num_rows):
                col = table.Column(i)
                self.rows.append((col.name, wx_value_type_map[col.type]))
            self.notify_get_values()
        else:
            # make the grid empty
            self.num_rows = 0
            self.rows = []

        # notify the views if the number of rows has changed
        if self.num_rows > old_num_rows:
            self.notify_append_rows(self.num_rows - old_num_rows)
        elif self.num_rows < old_num_rows:
            self.notify_delete_rows(0, old_num_rows - self.num_rows)

    def notify_append_rows(self, num):
        """Tell the view that num rows were appended"""
        self.send_view_message(wxGRIDTABLE_NOTIFY_ROWS_APPENDED, num)

    def notify_delete_rows(self, start, num):
        """Tell the view that num rows were deleted starting at start"""
        self.send_view_message(wxGRIDTABLE_NOTIFY_ROWS_DELETED, start, num)

    def notify_get_values(self):
        """Tell the view that the grid's values have to be updated"""
        self.send_view_message(wxGRIDTABLE_REQUEST_VIEW_GET_VALUES)

    def send_view_message(self, msgid, *args):
        """Send the message msgid to the view with arguments args"""
        view = self.GetView()
        if view:
            #print "send_view_message", msgid, args
            msg = apply(wxGridTableMessage, (self, msgid) + args)
            view.ProcessTableMessage(msg)

    #
    # 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 row >= self.num_rows or col >= self.num_cols

    # 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):
        if row < self.num_rows:
            return self.record[self.rows[row][0]]
        return ""

    def SetValue(self, row, col, value):
        if row < self.num_rows:
            name = self.rows[row][0]
            self.record[name] = value
            self.table.write_record(self.record_index, {name: value})

    #
    # Some optional methods
    #

    # Called when the grid needs to display labels
    def GetColLabelValue(self, col):
        return _("Value")

    def GetRowLabelValue(self, row):
        if row < self.num_rows:
            return self.rows[row][0]
        return ""

    # 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):
        # for some reason row and col may be negative sometimes, but
        # it's probably a wx bug (filed as #593189 on sourceforge)
        if 0 <= row < self.num_rows:
            return self.rows[row][1]
        return wxGRID_VALUE_STRING

    # 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)



class RecordGridCtrl(wxGrid):

    """Grid view for a RecordTable"""

    def __init__(self, parent, table = None, record = None):
        wxGrid.__init__(self, parent, -1)

        self.table = RecordTable(table, record)

        # 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.SetMargins(0,0)
        self.AutoSizeColumn(0, True)

        #self.SetSelectionMode(wxGrid.wxGridSelectRows)

        #EVT_GRID_RANGE_SELECT(self, self.OnRangeSelect)
        #EVT_GRID_SELECT_CELL(self, self.OnSelectCell)

    def SetTableRecord(self, table, record):
        self.table.SetTable(table, record)
