"""Canvas Factories are mixin classes to handel dealing with the slight
differences between each different matplotlib backend
"""
import sys

if not sys.modules.has_key('gtk'):
  import pygtk
  pygtk.require('2.0')
import gtk
import gtk.glade

from CanvasFactory import CanvasFactory
from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg


class CanvasFactoryGTK(CanvasFactory):
  """Canvas Factories are mixin classes to handel dealing with the slight
  differences between each different matplotlib backend

  This is the one for GTK
  """

  
  def __init__(self, container=None):
    """Initialize the gui environment needed by this canvas
    """
    CanvasFactory.__init__(self)
    if container is not None:
      self.gtk_win = container
    else:
      self.gtk_win = None
    self.widgets = {}
    self.canvass = {}
    self.statusbar_contexts = {}
      
  def createCanvas(self, figure, parent=None):
    canvas = self.canvass.setdefault(figure, FigureCanvasGTKAgg(figure))
    win = self.getWindow(figure, parent)
      
    # if we loaded the widgets go ahead and stick the canvas on it
    widgets = self.widgets.get(figure, None)
    if widgets is not None:
      print "widgets not none"
      vbox = widgets.get_widget('vboxMain')
      vbox.pack_start(canvas, gtk.TRUE, gtk.TRUE)
      vbox.show()

      statusbar = widgets.get_widget('statusbar')
      vbox.reorder_child(statusbar,-1)
    return canvas

  def getStatusbar(self, figure):
    """Get the statusbar object for whichever window we're working with
    """
    statusbar= CanvasFactory.getStatusbar(self, figure)
    if statusbar is not None:
      return statusbar
    
    widgets = self.widgets.get(figure, None)
    if widgets is None:
      return None
    return widgets.get_widget('statusbar')

  def getStatusbarContext(self, figure, context):
    """return the statusbar context id for a particular string
    """
    
    statusbar = self.getStatusbar(figure)
    return self.statusbar_contexts.setdefault(context,
                                             statusbar.get_context_id(context))
    #statusbar.get_context_id("iplot")

  def getIPlot(self, *args, **kwargs):
    """Return an IPlot class object
    """
    import IPlotGTK
    return apply(IPlotGTK.IPlotGTK, *args, **kwargs)

  def getWindow(self, figure, parent=None):
    """Return reference to an object we can draw on
    """
    if parent is None:
      if not self.widgets.has_key(figure):
        widgets = gtk.glade.XML('iplot.glade')
        gtk_win = widgets.get_widget('windowMain')
        #gtk_win.connect("destroy", gtk.mainquit)
        self.widgets[figure] = widgets
        return gtk_win
      else:
        return self.widgets[figure].get_widget('windowMain')
    else:
      return parent

  def getWidgets(self, figure):
    """Return glade widgets for a particular figure
    """
    return self.widgets.get(figure, None)
