from django.template import Context, loader
from django.http import HttpResponse
import Image, ImageDraw
import StringIO
import urllib

def spark(request, results):
    results = [float(i) for i in results.split(',')]
    origmax = max(results)
    origmin = min(results)
    if 0 == origmax-origmin:
       return
    else: 
       results = [i - origmin for i in results]
       results = [i * 100./(origmax-origmin) for i in results]
    im = Image.new("RGB", (len(results)+2, 20), 'white')
    draw = ImageDraw.Draw(im)
    coords = zip(range(len(results)), [15. - y/10. for y in results])
    draw.line(coords, fill="#888888")
    min_pt = coords[results.index(min(results))]
    draw.rectangle([min_pt[0]-1, min_pt[1]-1, min_pt[0]+1, min_pt[1]+1], fill="#0000FF")
    max_pt = coords[results.index(max(results))]
    draw.rectangle([max_pt[0]-1, max_pt[1]-1, max_pt[0]+1, max_pt[1]+1], fill="#FF0000")
    del draw
    f = StringIO.StringIO()
    im.save(f, "PNG")
    return HttpResponse("data:image/png,%s" % urllib.quote(f.getvalue()))


