from django import template
import re

register = template.Library()

class YoutubeNode(template.Node):
    """Convenient tag, allowing only having a normal watch link, from yotube, 
    embed video in html."""
    
    def __init__(self, parsed_link):
        self.parsed_link = parsed_link
            
    def render(self, context):
        del_it = re.compile('(&amp.*)')
        replace_it = re.compile('watch\?v=')
        link = self.parsed_link.render(context)
        link = del_it.sub('', link)
        link = replace_it.sub('embed/', link)
        video = """<iframe width="540" height="432" src="%s" 
        frameborder="0" allowfullscreen></iframe>""" % link
        return video

@register.tag
def youtube(parser, token):    
    parsed_link = parser.parse(('endyoutube',))
    # first token it's closing tag. delete_first_token 
    # just delete it - del self.tokens[0];)
    print type(parsed_link)
    parser.delete_first_token()
    return YoutubeNode(parsed_link)