import sys
import inspect
from django import template
from django.conf import settings
from django.utils.datastructures import SortedDict
from django.utils.encoding import smart_str
from django.utils.html import escape
from django.utils.safestring import mark_safe, SafeData

register = template.Library()

#
# {% chart %}
#

@register.tag
def chart(parser, token):
    bits = iter(token.split_contents())
    name = bits.next()
    varname = None
    saveas = None
    extends = None
    for bit in bits:
        if bit == "as":
            varname = bits.next()
        elif bit == "saveas":
            raise template.TemplateSyntaxError("Sorry, 'saveas' isn't implemented yet!")
            saveas = template.Variable(bits.next())
        elif bit == "extends":
            extends = template.Variable(bits.next())
        else:
            raise template.TemplateSyntaxError("Unknown argument to '%s': '%s'" % (name, bit))
    nodelist = parser.parse("end%s" % name)
    parser.delete_first_token()
    return ChartNode(nodelist, varname, saveas, extends)

class ChartNode(template.Node):

    def __init__(self, nodelist, varname, saveas, extends):
        self.nodelist = nodelist
        self.saveas = saveas
        self.varname = varname
        self.extends = extends

    def render(self, context):
        c = Chart()
        if self.extends:
            try:
                parent = self.extends.resolve(context)
            except template.VariableDoesNotExist:
                pass
            else:
                c = parent.clone()
                
        for node in self.nodelist:
            if isinstance(node, ChartDataNode):
                c.datasets.extend(node.resolve(context))
            elif isinstance(node, ChartOptionNode):
                node.update_chart(c, context)
            elif isinstance(node, AxisNode):
                c.axes.append(node.resolve(context))

        if self.varname:
            context[self.varname] = c
            return ""
        else:
            return c.img()

class Chart(object):

    BASE = "http://chart.apis.google.com/chart"
    defaults = {
        "chs": "200x200",
        "cht": "lc"
    }

    def __init__(self):
        # Use a SortedDict for the opeions so they are added in a
        # deterministic manner; this eases things like dealing with cache keys 
        # or writing unit tests.
        self.options = SortedDict()
        self.datasets = []
        self.axes = []
        self.datarange = None
        self.alt = None

    def clone(self):