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 += '<br /><br /><p class="text-center">...</p>'
            cntnt += f'<a href="{reverse_view_url}" style="float: right;" class="mt-4 button">Czytaj dalej</a>'
            cntnt += '<hr class="not-prose" style="border-color: white; margin: 3rem 0;" />'

        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('->')
                target = 'target="_blank" rel="norefferer noopener"'
            else:
                text, url = line.split('|')
                target = 'target="_self"'

            stripped = text.strip()
            return f'<a href={url} {target} class="inline px-14 py-2 button red color">{stripped}</a>' if stripped else ''
        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]))
