# -*- coding: utf-8 -*-
# GitHub http://gist.github.com/3247
from django import template
from django.template import resolve_variable

register = template.Library()

'''
ROR link_to_remote clone

Example 1:
{% ajax %}
link_to_remote 
  url => /dashboard/serverstatus/
  update => #server_status_body
  data => maxcount=10
{% endajax %}

Example 2:
{% ajax %}
link_to_remote 
	url => /dashboard/server/
	update => #server
{% endajax %}

Example 3:
{% ajax %}
link_to_remote
	condition => $("#serverstatus_more").click
	url => /dashboard/serverstatus/
	update => #server_status_body
	data => maxcount=15
	success => if(msg!="")$("#serverstatus_more").css("display","")
{% endajax %}
'''

def parseAjaxCmd(output):
    """parse ajax command"""
    ajax_template={'link_to_remote':'''
<script>
%(condition)s(function(){
	$.ajax({
		type:'GET',
		url:'%(url)s',
		dataType:'html',
		data: "%(data)s",
		success: function(msg){
			$("%(update)s").html(msg)
			%(success)s
		}
	})
})
</script>
    '''}
    output=filter(lambda x:x!='',
        map(lambda x:x.strip(),
            output.split('\n')
        )
    )
    ajaxcmd,params=output[0],output[1:]
    tmpl=ajax_template.get(ajaxcmd,'')
    if tmpl=='':return ''
    param_dict={'condition':'$(document).ready',
            'url':'/','data':'','update':'results',
            'success':''}
    param_dict.update(
        dict( [(k.strip(),v.strip()) for k,v in [p.split("=>") for p in params]] )
    )
    print "param_dict",param_dict
    script=tmpl%param_dict
    print script
    return script

class AjaxTagsNode(template.Node):
    def __init__(self,nodelist):
        self.nodelist = nodelist
    def render(self, context):
        output = self.nodelist.render(context)
        return parseAjaxCmd(output)

@register.tag('ajax')
def ajaxtag(parser, token):
    """
    {% ajax %}
    {% endajax %}
    """
    nodelist = parser.parse(('endajax',))
    parser.delete_first_token()
    return AjaxTagsNode(nodelist)