import logging
from django.conf import settings
from rest_framework.authentication import (
    SessionAuthentication,
    TokenAuthentication,
)
from rest_framework_simplejwt.authentication import JWTAuthentication

logger = logging.getLogger(__name__)


class LCSessionAuthentication(SessionAuthentication):
    """
    Class to disable CSRF validation.
    """

    def enforce_csrf(self, request):
        if settings.DEBUG:
            return
        return super().enforce_csrf(request)


class LCTokenAuthentication(TokenAuthentication):
    """
    Subclass to change header keyword.

    This Class cannot be in the api package because
    it fails in import in the settings.py file.
    """

    keyword = settings.AUTH_HEADER_NAME


class LCJWTAuthentication(JWTAuthentication):
    """
    Subclass check for restframework authtoken Tokens.

    If such tokens are found, then LCTokenAuthentication should be used.
    Otherwise, this class's behavior should remain in place, raising all
    the expected errors for expired JWT tokens.
    """

    def get_raw_token(self, header):
        """
        JWT tokens have 3 segments, separated by dots,
        while TokenAuthentication is a simple hash value.
        """
        if not (raw_token := super().get_raw_token(header)) or str(raw_token).count('.') != 2:
            return

        return raw_token


__all__ = (
    'LCSessionAuthentication',
    'LCTokenAuthentication',
    'LCJWTAuthentication',
)
