import re

from django import template

register = template.Library()


class NoSpacesNode(template.Node):
    """A template node that remove all spaces.

    Used by the ``nospaces`` templatetag.

    """

    spaces = re.compile('\s')

    def __init__(self, nodelist):
        self.nodelist = nodelist

    def render(self, context):
        return self.spaces.sub('', self.nodelist.render(context).strip())


@register.tag
def nospaces(parser, token):
    """ Removes all whitespaces in the templatetag.

    Example
    -------

        <div class="{% nospaces %}
            {% if foo %}
                foo
            {% else %}
                bar
            {% endif %}
        {% endnospaces %}">


    This example would return this HTML::

        <div class="foo">

    """

    nodelist = parser.parse(('endnospaces',))
    parser.delete_first_token()
    return NoSpacesNode(nodelist)


class ReduceSpacesNode(template.Node):
    """A template node that remove all spaces.

    Used by the ``reducespaces`` templatetag.

    """
    spaces = re.compile('\s+')

    def __init__(self, nodelist):
        self.nodelist = nodelist

    def render(self, context):
        return self.spaces.sub(' ', self.nodelist.render(context).strip())


@register.tag
def reducespaces(parser, token):
    """Replace many whitespace by one space in the templatetag.

    Example
    -------

        {% reducespaces %}
        <div
            class="foo
                   bar"
            id="baz"
            data-foo="bar"
            data-baz="qux"
        >
        {% endnospaces %}"


    This example would return this HTML::

        <div class="foo bar" id="baz" data-foo="bar" data-baz="qux" >
    """
    nodelist = parser.parse(('endreducespaces',))
    parser.delete_first_token()
    return ReduceSpacesNode(nodelist)


@register.simple_tag
def get_verbose_field_name(instance, field_name):
    """Returns the instance fields verbose_name."""
    return instance._meta.get_field(field_name).verbose_name.title()