from django import template
from django.urls.base import reverse_lazy, resolve
from django.utils.safestring import mark_safe
import re

register = template.Library()


@register.filter
def tableoverflow(value):
    return re.sub(r'<\/table>', '</table></div>', re.sub(r'<table[^>]*?>', '<div style="overflow-x: auto">\g<0>', value)) if value else ''


@register.simple_tag(takes_context=True)
def readmore(context, value: str):
    current_view = resolve(context.request.path).url_name

    if 'reverse' not in current_view:
        reverse_view_url = reverse_lazy(
            current_view + '-reverse', args=(value.id,))

        res = value.content.split('<!-- pagebreak -->')
        cntnt = res[0]
        if len(res) > 1:
            cntnt += f'<br /><br /><p class="text-center">...</p><a href="{reverse_view_url}" style="float: right;" class="button mt-4">Czytaj dalej</a>'

        return mark_safe(tableoverflow(cntnt))


@register.simple_tag()
def content(value: str):
    return mark_safe(tableoverflow(value.content))


@register.simple_tag()
def buttons(value: str):
    lines = value.split('\n')

    def parse(line: str) -> str:
        try:
            if '->' in line:
                text, url = line.split('->')
                return f'<a href={url} target="_blank" rel="norefferer noopener" class="inline px-12 py-2 button red color">{text}</a>'
            else:
                text, url = line.split('|')
                return f'<a href={url} target="_self" class="inline px-12 py-3 button red color">{text}</a>'
        except:
            return ''

    return mark_safe(''.join([parse(line) for line in lines]))


@register.filter()
def firstbutton(value: str):
    lines = value.split('\n')

    def parse(line: str) -> str:
        try:
            text, url = line.split('|' if '|' in line else '->')
            return url
        except:
            return ''

    return mark_safe(parse(lines[0]))
