from django import template
from django.template import Variable, VariableDoesNotExist

register = template.Library()

class IfContainsNode(template.Node):
	def __init__(self, iterable_name, val, nodelist_true, nodelist_false, negate):
		self.iterable, self.val = Variable(iterable_name), val
		self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
		self.negate = negate
	
	def __repr__(self):
		return "<IfContainsNode>"
		
	def render(self, context):
		try:
			iterable = self.iterable.resolve(context)
		except VariableDoesNotExist:
			iterable = []
		
		if (self.negate and self.val in iterable) or \
			(not self.negate and self.val in iterable):
			return self.nodelist_true.render(context)
		return self.nodelist_false.render(context)


@register.tag
def ifcontains(parser, token):
	return do_ifcontains(parser, token, False)

@register.tag
def ifnotcontains(parser, token):
	return do_ifcontains(parser, token, True)

def do_ifcontains(parser, token, negate):
	bits = list(token.split_contents())
	if len(bits) != 3:
		raise template.TemplateSyntaxError, "%r takes two arguments" % bits[0]
	end_tag = 'end' + bits[0]
	nodelist_true = parser.parse(('else', end_tag))
	token = parser.next_token()
	if token.contents == 'else':
		nodelist_false = parser.parse((end_tag,))
		parser.delete_first_token()
	else:
		nodelist_false = template.NodeList()
	
	if not bits[2][0] == bits[2][-1] and bits[2][0] in ('"', "'"):
		raise template.TemplateSyntaxError, \
			"%r tag's third argument should be in quotes" % bits[0]

	return IfContainsNode(bits[1], bits[2][1:-1], nodelist_true, nodelist_false, negate)