# -*- coding: utf-8 -*-
import logging

from django.contrib import auth
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.signals import user_login_failed
from django.core.exceptions import PermissionDenied
from users.models import Apprentice

logger = logging.getLogger('popojutrze')


class ApprenticeModelBackend(ModelBackend):
    _email_as_username = True
    _user_classes = [Apprentice]

    @classmethod
    def direct_authenticate(cls, **credentials):
        backend = cls()
        user = None
        try:
            user = backend.authenticate(**credentials)
        except TypeError:
            pass
        except PermissionDenied:
            pass
        if user is not None:
            user.backend = '%s.%s' % (backend.__module__, backend.__class__.__name__)
            return user
        else:
            # The credentials supplied are invalid to all backends, fire signal
            user_login_failed.send(sender=__name__, credentials=auth._clean_credentials(credentials))

    def authenticate(self, username=None, password=None, **kwargs):
        for user_class in self._user_classes:
            try:
                if self._email_as_username:
                    user = user_class.objects.get(email=username)
                else:
                    user = user_class.objects.get(username=username)
            except user_class.DoesNotExist:
                continue
            if user.check_password(password):
                logger.info('User [%d] %s authorised by client backend!' % (user.id, username,))
                return user

    def get_user(self, user_id):
        for user_class in self._user_classes:
            try:
                user = user_class.objects.get(pk=user_id)
                return user
            except user_class.DoesNotExist:
                continue
        return None
