from django import template
from django.template import resolve_variable
from exodus import wllogic

register = template.Library()

class NetworkNode(template.Node):
	def __init__(self, address, subnet):
		self.address = address
		self.subnet = subnet
	def render(self, context):
		return (wllogic.get_network(resolve_variable(self.address, context), \
                resolve_variable(self.subnet,context)))

class BroadcastNode(template.Node):
	def __init__(self, address, subnet):
		self.address = address
		self.subnet = subnet
	def render(self, context):
		return (wllogic.get_broadcast(resolve_variable(self.address, context), \
                resolve_variable(self.subnet,context)))

@register.tag
def network(parser, token):
    try:
        # split_contents() knows not to split quoted strings.
        tag_name, address, subnet = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires a two arguments" \
                % token.contents.split()[0]
    return NetworkNode(address, subnet)

@register.tag
def broadcast(parser, token):
    try:
        # split_contents() knows not to split quoted strings.
        tag_name, address, subnet = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires a two arguments" \
                % token.contents.split()[0]
    return BroadcastNode(address, subnet)

@register.filter
def subnet(value):
	return wllogic.get_subnet(value)
