# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-12-17 10:48
from __future__ import unicode_literals
import re

from bs4 import BeautifulSoup
from django.db import migrations

URL_NAME_RE = r"url '(\w+)'"


def replace_setting_urls(apps, schema_editor):
    SettingValueTranslation = apps.get_model("core", "SettingValueTranslation")
    settings = SettingValueTranslation.objects.filter(
        master__setting__group__name="email"
    )
    for s in settings:
        fix_url(s)


def fix_url(setting):
    """Replaces anchor urls in a setting value with a django variable

    The django variable is built from the url name, appending "_url" at the end
    e.g:
        {% journal_url 'some_view' param, param2 %} => {{ some_view_url }}
    If a django variable was already in use, then we just unwrap the anchor:
        '<a href="{{ url }}">here</a>' => 'here: {{ url }}'
    The text in the anchor tag is preserved when it is not a django var
        '<a href="{{ url }}">{{ url }}</a>' => '{{ url }}'

    """
    value = setting.value
    # BS4 will auto close <br> tags by appending a number of </br> at the end
    # so we autoclose the tags ourselves instead
    value = value.replace("<br>", "<br />")
    soup = BeautifulSoup(value, "html.parser")
    for anchor_tag in soup.findAll("a"):
        href = anchor_tag.get("href")
        text = anchor_tag.text
        match = re.search(URL_NAME_RE, href)
        new_text = None
        if match:
            url_name = match.group(1)
            if "%" in text:
                new_text = "{{ %s_url }}" % (url_name)
            else:
                new_text = "%s: {{ %s_url }}" % (text, url_name)
        elif href.startswith("{"):
            if "{" in text:
                new_text = href
            else:
                new_text = "%s: %s" % (text, href)

        if new_text:
            anchor_tag.replace_with(new_text)
            setting.value = str(soup)
            setting.save()


class Migration(migrations.Migration):
    dependencies = [
        ("core", "0044_auto_20201210_1140"),
    ]

    operations = [
        migrations.RunPython(
            replace_setting_urls, reverse_code=migrations.RunPython.noop
        ),
    ]
