import Tkinter
#from django.template import RequestContext
from django.template import Template
#from django.template.loaders import app_directories

class TclTemplate(Template):
    interp = None

    def __init__(self, source):
        Template.__init__(self, source)
        self.interp = Tkinter.Tcl()
        self.source = source

    def assoc_ob(self, ob):
        def caller(*args):
            func = getattr(ob, args[0])
            return func()
        proc = self.interp.register(caller)
        #interp.setvar(var, proc)
        return proc
        
    def render(self, context):
        # flatten the Django Context into a single dictionary.
        context_dict = {}
        for (k, v) in context.iteritems():
            if type(v).__name__ == 'instance':
                v = self.assoc_ob(v)
        self.interp.setvar(k, v)

        return self.interp.call("subst", self.source)

        for d in context.dicts:            
            context_dict.update(d)
        l = dict_to_list(context_dict)
        return super(Template, self).render(context_dict)


# class TclTemplateLoader(BaseLoader):
#     is_usable = True

#     def load_template(self, template_name, template_dirs=None):
#         source, origin = self.load_template_source(template_name, template_dirs)
#         template = TclTemplate(source)
#         return template, origin
