from waveapi import events
from waveapi import model
from waveapi import robot
from waveapi import document
import StringIO
import urllib
from google.appengine.api import urlfetch

def plot_sparkline3(rs):
   try:
      return urlfetch.fetch('http://lee-phillips.org/services/spark/%s/' % rs).content
   except:
      return 'Error fetching.'

def OnParticipantsChanged(properties, context):
  """Invoked when any participants have been added/removed."""
  added = properties['participantsAdded']
  for p in added:
    Notify(context)

def OnRobotAdded(properties, context):
  """Invoked when the robot has been added."""
  root_wavelet = context.GetRootWavelet()
  root_wavelet.CreateBlip().GetDocument().SetText("Plotzie is alive!")

def Notify(context):
  root_wavelet = context.GetRootWavelet()
  root_wavelet.CreateBlip().GetDocument().SetText('Greetings from plotzie. To plot a sparkline, type "[sl[0,-2,1.e-2,2.]]", with your own numbers, of course.')

def OnBlipSubmitted(properties, context):
   """Invoked when a blip has been added."""
   blip = context.GetBlipById(properties['blipId']) 
   blip_text_view = blip.GetDocument()
   t = blip_text_view.GetText()
   (t1,t2) = (t.find('[sl['), t.find(']]'))
   if t1 > -1 and t2 > t1+5: #Looks like a sparkline
      rs = t[t1+4:t2]
      blip_text_view.DeleteRange(document.Range(t1, t2+2))
      rs = [float(i) for i in rs.split(',')]
      origrs = rs
      origmax = max(rs)
      origmin = min(rs)
      if 0 == origmax-origmin:
         return
      else:
         rs = [i - origmin for i in rs]
         rs = [i * 100./(origmax-origmin) for i in rs]
         rs = ','.join([str(i) for i in rs])
      spark = document.Image(url = plot_sparkline3(rs), caption = str(origrs))
      blip_text_view.InsertElement(t1, spark)

if __name__ == '__main__':
  myRobot = robot.Robot('plotzie', 
      image_url='http://lee-phillips.org/plotzieface.png',
      version='2',
      profile_url='http://plotzie.appspot.com/')
  myRobot.RegisterHandler(events.WAVELET_PARTICIPANTS_CHANGED, OnParticipantsChanged)
  myRobot.RegisterHandler(events.BLIP_SUBMITTED, OnBlipSubmitted)
  myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded)
  myRobot.Run()

