import logging

from django_yauth.authentication_mechanisms.tvm import Mechanism as BaseTvmMechanism


logger = logging.getLogger(__name__)


class Mechanism(BaseTvmMechanism):
    """
    Used to provide authentication by debug_uid header.

    This is required for local Next development.
    More info FEMIDA-7166
    """
    debug_uid = 'HTTP_DEBUG_UID'
    # To provide compatibility with the base tvm auth mechanism
    mechanism_name = 'tvm'

    def extract_params(self, request):
        params = super().extract_params(request)

        uid = request.META.get(self.debug_uid)

        if uid:
            params['uid'] = uid

        return params

    def apply(self, service_ticket, user_ip, user_ticket=None, uid=None):
        parsed_user_ticket = None
        parsed_service_ticket = self.tvm.parse_service_ticket(service_ticket)
        if user_ticket is not None:
            parsed_user_ticket = self.tvm.parse_user_ticket(user_ticket)

        if not parsed_service_ticket:
            logger.warning('Request with not valid service ticket was made')
        elif not parsed_user_ticket and user_ticket is not None:
            logger.warning('Request with not valid user ticket was made')
        else:
            if parsed_user_ticket or uid:
                return self.get_impersonated_user(
                    user_ticket=parsed_user_ticket,
                    service_ticket=parsed_service_ticket,
                    raw_user_ticket=user_ticket,
                    raw_service_ticket=service_ticket,
                    user_ip=user_ip,
                    uid=uid,
                )
            else:
                return self.get_service_user(
                    service_ticket=parsed_service_ticket,
                    raw_service_ticket=service_ticket,
                    user_ip=user_ip,
                )

        return self.anonymous()

    def get_impersonated_user(
        self,
        user_ticket,
        service_ticket,
        raw_user_ticket,
        raw_service_ticket,
        user_ip,
        uid,
    ):
        if uid and user_ticket is None:
            logger.info('authenticate by debug_uid')
            return self.YandexUser(
                user_ticket=user_ticket,
                service_ticket=service_ticket,
                uid=uid, mechanism=self,
                raw_user_ticket=raw_user_ticket,
                raw_service_ticket=raw_service_ticket,
                user_ip=user_ip,
            )
        else:
            return super().get_person_user(
                user_ticket=user_ticket,
                service_ticket=service_ticket,
                raw_user_ticket=raw_user_ticket,
                raw_service_ticket=raw_service_ticket,
                user_ip=user_ip,
            )
