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

__version__ = "$Revision: 2700 $"

import wx
from wx import grid

from Thuban import _

from dialogs import NonModalDialog
from controls import RecordListCtrl, RecordGridCtrl
from messages import SHAPES_SELECTED
import main

class IdentifyListCtrl(RecordListCtrl):

    def selected_shape(self, layer, shape):
        if layer is not None:
            table = layer.ShapeStore().Table()
        else:
            table = None
        self.fill_list(table, shape)

class IdentifyGridCtrl(RecordGridCtrl):

    def selected_shape(self, layer, shape):
        if layer is not None:
            table = layer.ShapeStore().Table()
        else:
            table = None
        self.SetTableRecord(table, shape)

class IdentifyView(NonModalDialog):

    ID_STOP = 100

    def __init__(self, parent, name):
        NonModalDialog.__init__(self, parent, name, _("Identify Shape"))
        parent.Subscribe(SHAPES_SELECTED, self.selected_shape)

        top_box = wx.BoxSizer(wx.VERTICAL)
        if main.options.attribute_editing_enabled:
            self.list = IdentifyGridCtrl(self)
        else:
            self.list = IdentifyListCtrl(self, -1)
        self.list.SetSize(wx.Size(305,200))
        top_box.Add(self.list, 1, wx.EXPAND|wx.ALL, 4)

        box = wx.BoxSizer(wx.HORIZONTAL)
        box.Add(wx.Button(self, wx.ID_CLOSE, _("Close Window")), 0, wx.ALL, 4)
        box.Add(wx.Button(self, self.ID_STOP, _("Stop Identify Mode")),
                         0, wx.ALL, 4)
        top_box.Add(box, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALL, 4)

        self.Bind(wx.EVT_BUTTON, self.OnClose, id=wx.ID_CLOSE)
        self.Bind(wx.EVT_BUTTON, self.OnStop, id=self.ID_STOP)

        self.SetAutoLayout(True)
        self.SetSizer(top_box)
        top_box.Fit(self)
        top_box.SetSizeHints(self)

        # Make sure to reflect the current selection.
        self.selected_shape(parent.SelectedLayer(), parent.SelectedShapes())

    def OnClose(self, event):
        self.parent.Unsubscribe(SHAPES_SELECTED, self.selected_shape)
        NonModalDialog.OnClose(self, event)

    def OnStop(self, event):
        self.parent.Unsubscribe(SHAPES_SELECTED, self.selected_shape)
        self.parent.canvas.SelectTool(None)
        NonModalDialog.OnClose(self, event)

    def selected_shape(self, layer, shapes):
        """Subscribed to the SHAPES_SELECTED messages.

        If exactly one shape is selected, pass that shape id to the
        list's selected_shape method. Otherwise pass None as the shape
        id.
        """
        if len(shapes) == 1:
            shape = shapes[0]
        else:
            shape = None
        self.list.selected_shape(layer, shape)
