# -*- coding: utf-8 -*-
# Copyright (c) 2016 Aladom SAS & Hosting Dvpt SAS
from django.template import Library, Node, Context, Template
from django.template.defaulttags import token_kwargs
from django.template.exceptions import (
    TemplateDoesNotExist, TemplateSyntaxError,
)
from django.template.loader import get_template


register = Library()


class TagNode(Node):

    def __init__(self, nodelist, tag_name, extra_context=None):
        self.nodelist = nodelist
        self.tag_name = tag_name
        self.extra_context = extra_context or {}

    def get_template(self):
        template_name = 'mailing/html_tags/{}.html'.format(self.tag_name)
        try:
            template = get_template(template_name)
        except TemplateDoesNotExist:
            template = Template(
                "<{{ tag_name }}>{{ content }}</{{ tag_name }}>")
        return template

    def render(self, context):
        content = self.nodelist.render(context)
        self.extra_context['tag_name'] = self.tag_name
        self.extra_context['content'] = content
        template_context = Context(self.extra_context)
        template = self.get_template()
        return template.render(template_context)


@register.tag(name="tag")
def make_tag(parser, token):
    nodelist = parser.parse(('endtag',))
    parser.delete_first_token()
    tokens = token.split_contents()

    try:
        tag_name = tokens[1]
    except IndexError:
        raise TemplateSyntaxError(
            "'{}' tag requires at least 1 argument.".format(tokens[0]))

    if tag_name[0] != tag_name[-1] or tag_name[0] not in ['"', "'"]:
        raise TemplateSyntaxError(
            "'{}' tag's first argument should be in quotes.".format(tokens[0]))
    tag_name = tag_name[1:-1]

    options = {}
    remaining_bits = tokens[2:]
    while remaining_bits:
        option = remaining_bits.pop(0)
        if option in options:
            raise TemplateSyntaxError(
                "The '{}' option was specified more than once.".format(option))
        if option == 'with':
            value = token_kwargs(remaining_bits, parser, support_legacy=True)
            if not value:
                raise TemplateSyntaxError(
                    "'with' in {} tag needs at least one "
                    "keyword argument.".format(tokens[0]))
        else:
            raise TemplateSyntaxError(
                "Unknown argument for {} tag: {}".format(tokens[0], option))
        options[option] = value

    extra_context = options.get('with', {})

    return TagNode(nodelist, tag_name, extra_context)

@@ -961,35 +961,96 @@
         
-self.extra_context%5B
+template = self.get_template()%0A        template_context = Context(%7B%0A            
 'tag_nam
@@ -1051,19 +1051,17 @@
 ag_name'
-%5D =
+:
  self.ta
@@ -1058,32 +1058,33 @@
 ': self.tag_name
+,
 %0A        self.ex
@@ -1080,27 +1080,12 @@
     
-self.extra_context%5B
+    
 'con
@@ -1093,19 +1093,17 @@
 ent'
-%5D =
+:
  content
 %0A   
@@ -1102,44 +1102,109 @@
 tent
-%0A
+,%0A  
       
-  template_context = Context(
+%7D)%0A        values = dict((key, val.resolve(context)) for key, val in%0A                      
 self
@@ -1213,24 +1213,32 @@
 xtra_context
+.items()
 )%0A        te
@@ -1231,32 +1231,37 @@
 ())%0A        
+with 
 template
  = self.get_
@@ -1248,39 +1248,45 @@
 template
- = self.get_template()%0A
+_context.push(**values):%0A    
         
@@ -2228,29 +2228,8 @@
 rser
-, support_legacy=True
 )%0A  
@@ -2326,18 +2326,20 @@
 ith' in 
+'
 %7B%7D
+'
  tag nee
@@ -2506,18 +2506,20 @@
 ent for 
+'
 %7B%7D
+'
  tag: %7B%7D

Resolve 'with' token_kwargs - Fixed #3