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

import Tkinter as Tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

import CanvasFactory

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

  This is the one for Tkinter
  """

  TK_ROOT = None
  
  def __init__(self, container=None):
    """Initialize the gui environment needed by this canvas
    """
    CanvasFactory.CanvasFactory.__init__(self)

    if container is not None:
      self.TK_ROOT = container

  def createCanvas(self, figure, parent=None):
    """create the canvas for a particular figure
    """
    canvas = FigureCanvasTkAgg(figure, master=self.getWindow(parent))
    canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

    #canvas_widget = canvas.get_tk_widget()
    #statusBar = Pmw.MessageBar(canvas_widget, entry_relief='groove')
    #statusBar = Pmw.MessageBar(self.getWindow(parent), entry_relief='groove')
    #statusBar.pack(fill='x')
    self.canvass[figure] = canvas
    #self.statusbars[figure] = statusBar
    return canvas
   
  def getIPlot(self, *args, **kwargs):
    """Return an IPlot class object
    """
    import IPlotTk
    return apply(IPlotTk.IPlot, args, kwargs)

  def getDatasetPlot(self, *args, **kwargs):
    import IPlotTk
    return apply(IPlotTk.DatasetPlot, args, kwargs)
  
  def getWindow(self, figure, parent=None):
    """Return reference to an object we can draw on
    """
    if parent is None:
      if self.TK_ROOT is None:
        self.startIPlot()
      return self.TK_ROOT
    else:
      return parent
      
  def destroy(self, e): sys.exit()

  def startIPlot(self, showSplash=0):
    """
    Simple Setup function to setup a psedo Tk-application for all widgets to belong to.
    """
    if self.TK_ROOT is None:
      print "Starting IPlotTk..."
      self.TK_ROOT = Tk.Tk(className = 'IPlot')
      #TK_ROOT.withdraw()
      #self.TK_ROOT.bind("<Destroy>", self.destroy)
      
      if showSplash:
        import time
        splash = Tk.Toplevel()
        splash.title('Welcome to IPlot')
        text = Tk.Label(splash, 
                        font=('Helvetica', 16, 'bold'),
                        relief = 'raised',
                        text = 'Welcome to IPlot...'
                        '\n\n'
                        'Written By: \n'
                        'Christopher Hart \n'
                        'Caltech Biology'
                        )
        text.pack(fill = 'both', expand=1)
        self.TK_ROOT.update()
        splash.update_idletasks()
        splash.deiconify()
        self.TK_ROOT.update()
        time.sleep(1)
        splash.destroy()

    return self.TK_ROOT
        
