from django.conf import settings
from django.urls import reverse
from django.utils.timezone import localtime, now
from django.utils.text import slugify
from django.utils.translation.trans_real import language_code_prefix_re

from .settings import SEO_USE_URL_FULL_PATH

__all__ = (
    'image_upload_to',
    'admin_change_url',
    'get_path_from_request'
)


def image_upload_to(instance, filename: str) -> str:
    """
    Util to set upload_to path,
    based on model's class name and date of uploading for image field
    """
    tz_now = localtime(now()).strftime('%Y/%m/%d')
    return f"{slugify(instance.__class__.__name__)}/{tz_now}/{filename}"


def admin_change_url(obj) -> str:
    """
    Return admin change url for given object
    """
    app_label = obj._meta.app_label
    model_name = obj._meta.model.__name__.lower()
    return reverse(f'admin:{app_label}_{model_name}_change', args=(obj.pk,))


def get_path_from_request(request, full_path: bool = SEO_USE_URL_FULL_PATH):
    """
    Return current path from request, excluding language code
    """
    if full_path:
        path = request.get_full_path()
    else:
        path = request.path

    regex_match = language_code_prefix_re.match(path)

    if regex_match:
        lang_code = regex_match.group(1)
        languages = [
            language_tuple[0] for
            language_tuple in settings.LANGUAGES
        ]
        if lang_code in languages:
            path = path[1 + len(lang_code):]
            if not path.startswith('/'):
                path = '/' + path

    return path
