from django import template
from django.utils.safestring import mark_safe
from django.utils.html import format_html

register = template.Library()

# Tag simples: <div class="header-top">...</div>
class SimpleBlockNode(template.Node):
    def __init__(self, nodelist, tag_open, tag_close):
        self.nodelist = nodelist
        self.tag_open = tag_open
        self.tag_close = tag_close

    def render(self, context):
        content = self.nodelist.render(context)
        return format_html('{}{}{}', mark_safe(self.tag_open), mark_safe(content), mark_safe(self.tag_close))

def create_simple_block(name, tag_open, tag_close):
    def tag_func(parser, token):
        nodelist = parser.parse(['end_' + name])
        parser.delete_first_token()
        return SimpleBlockNode(nodelist, tag_open, tag_close)
    register.tag(name, tag_func)

# Header raiz
create_simple_block('br_header', '<header class="br-header"><div class="container-lg">', '</div></header>')
create_simple_block('br_header_top', '<div class="header-top">', '</div>')
create_simple_block('br_header_bottom', '<div class="header-bottom">', '</div>')
create_simple_block('br_header_list', '<div class="header">', '</div>')
create_simple_block('br_list_title', '<div class="title">', '</div>')

# Ações
class ActionsNode(template.Node):
    def __init__(self, nodelist):
        self.nodelist = nodelist
    def render(self, context):
        content = self.nodelist.render(context)
        return format_html('<div class="header-actions">{}</div>', mark_safe(content))

@register.tag
def br_header_actions(parser, token):
    nodelist = parser.parse(['end_br_header_actions'])
    parser.delete_first_token()
    return ActionsNode(nodelist)

@register.simple_tag
def br_header_logo(src, alt, signature=""):
    logo_html = format_html('<img src="{}" alt="{}" />', src, alt)
    if signature:
        return format_html(
            '''<div class="header-logo">
                {}
                <span class="br-divider vertical"></span>
                <div class="header-sign">{}</div>
            </div>''',
            logo_html,
            mark_safe(signature)
        )
    else:
        return format_html('<div class="header-logo">{}</div>', logo_html)

class DropdownNode(template.Node):
    def __init__(self, nodelist, tag_name, class_name):
        self.nodelist = nodelist
        self.tag_name = tag_name
        self.class_name = class_name

    def render(self, context):
        content = self.nodelist.render(context)
        html = f'''
        <div class="{self.tag_name} {self.class_name}">
            <button class="br-button circle small" type="button" data-toggle="dropdown" aria-label="Abrir {self.tag_name.replace('-', ' ').title()}">
                <i class="fas {'fa-ellipsis-v' if 'links' in self.tag_name else 'fa-th'}" aria-hidden="true"></i>
            </button>
            <div class="br-list">
                {content}
            </div>
        </div>
        '''
        if 'links' in self.tag_name:
            html += '<span class="br-divider vertical mx-half mx-sm-1"></span>'
        return mark_safe(html)

def dropdown_tag(name, tag_class):
    def tag_func(parser, token):
        bits = token.split_contents()
        class_name = "dropdown"
        if len(bits) > 1:
            for bit in bits[1:]:
                if bit.startswith('class='):
                    class_name = bit.split('=')[1].strip('"\'')
        nodelist = parser.parse([f'end_{name}'])
        parser.delete_first_token()
        return DropdownNode(nodelist, tag_class, class_name)
    register.tag(name, tag_func)

dropdown_tag('br_header_links', 'header-links')
dropdown_tag('br_header_functions', 'header-functions')

class ItemNode(template.Node):
    def __init__(self, nodelist, href):
        self.nodelist = nodelist
        self.href = href

    def render(self, context):
        content = self.nodelist.render(context)
        href = self.href.strip('"\'')
        try:
            resolved_href = template.Variable(href).resolve(context)
        except template.VariableDoesNotExist:
            resolved_href = href
        return format_html('<a class="br-item" href="{}">{}</a>', resolved_href, mark_safe(content))

@register.tag
def br_item(parser, token):
    try:
        tag_name, href = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError('%r tag requires href argument' % token.contents.split()[0])
    nodelist = parser.parse(['end_br_item'])
    parser.delete_first_token()
    return ItemNode(nodelist, href)

@register.simple_tag
def br_function_item(icon, label):
    return format_html('''
    <div class="br-item">
        <button class="br-button circle small" type="button" aria-label="{0}">
            <i class="fas {1}" aria-hidden="true"></i>
            <span class="text">{0}</span>
        </button>
    </div>
    ''', label, icon)

@register.simple_tag
def br_header_search_trigger():
    return mark_safe('''
    <div class="header-search-trigger">
        <button class="br-button circle" type="button" aria-label="Abrir Busca" data-toggle="search" data-target=".header-search">
            <i class="fas fa-search" aria-hidden="true"></i>
        </button>
    </div>
    ''')

@register.simple_tag
def br_header_login():
    return mark_safe('<div class="header-login">')

@register.simple_tag
def end_br_header_login():
    return mark_safe('</div>')

@register.simple_tag
def br_button():
    return mark_safe('''
    <div class="header-sign-in">
        <button class="br-sign-in small" type="button" data-trigger="login">
            <i class="fas fa-user" aria-hidden="true"></i>
            <span class="d-sm-inline">Entrar</span>
        </button>
    </div>
    ''')

@register.simple_tag
def br_header_avatar(icon=""):
    return format_html('<div class="header-avatar">{}</div>', mark_safe(icon))

@register.simple_tag
def br_header_menu():
    return mark_safe('''
    <div class="header-menu">
        <div class="header-menu-trigger">
            <button class="br-button small circle" type="button" aria-label="Menu" data-toggle="menu" data-target="#main-navigation" id="navigation">
                <i class="fas fa-bars" aria-hidden="true"></i>
            </button>
        </div>
        <div class="header-info">
            <div class="header-title">Título do Header</div>
            <div class="header-subtitle">Subtítulo do Header</div>
        </div>
    </div>
    ''')

@register.simple_tag
def br_header_search():
    return mark_safe('''
    <div class="header-search">
        <div class="br-input has-icon">
            <label for="searchbox-114">Texto da pesquisa</label>
            <input id="searchbox-114" type="text" placeholder="O que você procura?"/>
            <button class="br-button circle small" type="button" aria-label="Pesquisar">
                <i class="fas fa-search" aria-hidden="true"></i>
            </button>
        </div>
        <button class="br-button circle search-close ml-1" type="button" aria-label="Fechar Busca" data-dismiss="search">
            <i class="fas fa-times" aria-hidden="true"></i>
        </button>
    </div>
    ''')
