import functools
import logging

from django.http import HttpResponse
from django.utils.translation import gettext as _
from rest_framework import exceptions, status
from rest_framework.authentication import BasicAuthentication

__all__ = ("oscar_auth",)

logger = logging.getLogger(__name__)

FEED_PASSWORD = "912cf9812ffaccc168c3f04722eb4b66060c2c99e467fe51"
FEED_USERNAME = "superuser"


class SimpleBasicAuthentication(BasicAuthentication):
    def authenticate_credentials(self, userid, password, request=None):
        if userid == FEED_USERNAME and password == FEED_PASSWORD:
            return True

        raise exceptions.AuthenticationFailed(_("Invalid username/password."))

    def check(self, request):
        if self.authenticate(request) is None:
            raise exceptions.AuthenticationFailed(_("Missing basic authentication"))


def oscar_auth(func):
    @functools.wraps(func)
    def wrapper(request):
        auth = SimpleBasicAuthentication()
        try:
            auth.check(request)
            return func(request)
        except exceptions.AuthenticationFailed:
            response = HttpResponse(status=status.HTTP_401_UNAUTHORIZED)
            response["WWW-Authenticate"] = auth.authenticate_header(request)
            return response

    return wrapper
