# -*- coding: utf-8 -*-
from django import template
from sampleapp import helper

register = template.Library()

@register.tag()
def if_render_facet_queries(parser, token):
  bits = list(token.contents.split())
  end_tag = 'end' + bits[0]
  nodelist = parser.parse((end_tag,))
  if len(bits) != 3:
    raise template.TemplateSyntaxError, "'%s' requires 2 arguments" % bits[0
]
  parser.delete_first_token()
  return IfRenderFacetQueriesNode(bits[1], bits[2],nodelist)

class IfRenderFacetQueriesNode(template.Node):
  def __init__(self, category, facet_queries, nodelist):
    self.category = category
    self.facet_queries = facet_queries
    self.nodelist = nodelist

  def render(self, context):
    output = ''
    category = template.resolve_variable(self.category, context)
    facet_queries = template.resolve_variable(self.facet_queries, context)
    if helper.get_facet_queries_sum_count(category,facet_queries) > 0:
      output = self.nodelist.render(context)
    return output


@register.tag()
def if_render_facet_query(parser, token):
  bits = list(token.contents.split())
  end_tag = 'end' + bits[0]
  nodelist = parser.parse((end_tag,))
  if len(bits) != 3:
    raise template.TemplateSyntaxError, "'%s' requires 2 arguments" % bits[0
]
  parser.delete_first_token()
  return IfRenderFacetQueryNode(bits[1], bits[2],nodelist)

class IfRenderFacetQueryNode(template.Node):
  def __init__(self, query, facet_queries, nodelist):
    self.query = query
    self.facet_queries = facet_queries
    self.nodelist = nodelist

  def render(self, context):
    output = ''
    query = template.resolve_variable(self.query, context)
    facet_queries = template.resolve_variable(self.facet_queries, context)
    if helper.get_facet_query_count(query,facet_queries) > 0:
      output = self.nodelist.render(context)
    return output



