from quixote import get_response, get_field
from quixote.errors import TraversalError
from quixote.directory import Directory

class PlotUI(Directory):
  _q_exports = ['', 'download', 'sendplot']
  supported_formats={'BMP' : 'image/x-ms-bmp',
                     'GIF' : 'image/gif',
                     'JPEG': 'image/jpeg',
                     #'PALM': 'application/vnd.palm',
                     #'PCX' : 'image/pcx',
                     'PDF' : 'application/pdf',
                     'EPS' : 'application/postscript',
                     #'PS'  : 'application/postscript'
                     'PNG' : 'image/png',
                     }
  sorted_formats = supported_formats.keys()
  sorted_formats.sort()
  vector_formats = ['PS', 'EPS', 'SVG']
  def __init__(self, datasource):
    self.datasource = datasource
    
  def _q_lookup(self, name):
    print "plotui_lookup", len(self.datasource), id(self.datasource)
    response = get_response()
    response.cache = 3600
    p = self.datasource.get_plot_by_id(name)
    if p is not None:
      response.set_content_type('image/png')
      plot = open(p.image_filename, 'rb').read()
      return plot
    else:
      response.set_status(404)
      return ""

  def download(self):
    """Prompt for download settings
    """
    plotid=get_field('plotid',None)
    if plotid is None:
      raise TraversalError("invalid url")
    p = self.datasource.get_plot_by_id(plotid)
    context = self.datamanagerui.create_context(self.datasource)
    context.addGlobal('plotid', p.id)
    context.addGlobal('format',html_combo_selection(self.sorted_formats,'PNG'))
    return get_template('downloadplot', context)
    
  def sendplot(self):
    """Send plot to user
    """
    plotid=get_field('plotid',None)
    format = get_field('format', 'PNG')
    print "sendplot", plotid, format
    response = get_response()
    response.set_content_type(self.supported_formats[format])
    plot = self.datasource.get_plot_by_id(plotid)
    if format in self.vector_formats:
      # do funky thing involving writing to a file
      # FIXME: support vector formats better
      return plot.iplot.tostring(format)
    else:
      # just grab tostring
      return plot.iplot.tostring(format)
      
    
