# Author:  Shwagroo Team
# Website: (http://django-gems.blogspot.com/)

from django.template import loader, RequestContext
from django.http import HttpResponse, Http404

from settings import DEBUG

decorator_with_args = lambda decorator: lambda *args, **kwargs: lambda func: decorator(func, *args, **kwargs )

templates = {}


def django_template_to_string( request, variables, template ):
    """
      usage:
      
      django_template_to_string( request, { 'title' : 'hello' }, "base.html" )
    """
    if not DEBUG:
        temp = templates.get( template )
        if temp is None:
            temp = loader.get_template(template)
            templates[template] = temp
        
    else:
        temp = loader.get_template(template)

    c = RequestContext(request)
    c.update(variables)
    return temp.render(c)

@decorator_with_args
def django_template(func, template=None):
    """
      usage:

      @django_template("moja_strona.html")
      def master_home(request):
          variables = { 'title' : "Hello World!" }
          return variables
    """
    def wrapper(request,*args,**kwargs):
        variables = func(request, *args, **kwargs )
        
        string = django_template_to_string( request, variables, template )

        return HttpResponse( string )
        
    wrapper.__name__ = func.__name__
    wrapper.__dict__ = func.__dict__
    wrapper.__doc__ = func.__doc__
    return wrapper