from typing import Callable, Optional

from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import user_passes_test


def export_permission_required(view_func: Optional[Callable] = None,
                               redirect_field_name: str = REDIRECT_FIELD_NAME,
                               login_url: str = 'admin:login') -> Callable:
    """
    За основу взят декоратор `staff_member_required`:
    https://docs.djangoproject.com/id/2.2/ref/contrib/admin/#the-staff-member-required-decorator
    """
    actual_decorator = user_passes_test(
        lambda u: u.is_superuser or (
            u.is_active
            and u.is_staff
            and u.has_perm('permissions.can_export_from_admin')
        ),
        login_url=login_url,
        redirect_field_name=redirect_field_name,
    )
    if view_func:
        return actual_decorator(view_func)
    return actual_decorator
