from django.template import Library
from django.urls import resolve, reverse
from django.utils.translation import activate, get_language

import re

import logging
logger = logging.getLogger(__name__)

register = Library()


@register.simple_tag(takes_context=True)
def change_lang(context, lang="de", *args, **kwargs):
    """
    Get active page's url by a specified language
    Usage: {% change_lang 'en' %}

    shamelessly stolen from stackoverflow:
    https://stackoverflow.com/a/41147772
    """
    logger = logging.getLogger(__name__)

    logger.debug(f"changing lang from '{lang}'")

    path = context['request'].get_raw_uri()
    url = path
    try:
        cur_lang: str = get_language()
        url = re.sub(f"/{cur_lang}/", f"/{lang}/", url)

    except Exception as e:
        logger.error(f"exception while building language switcher form: {e}")
        logger.debug(f"this is the context: {context}")

    finally:
        activate(lang)
        return "%s" % url

