from django.contrib.auth.models import User

class DummyUser(object):
    def __init__(self, user, delegate):
        self.user = user
        self.delegate = delegate
        self.id = '%s,%s' % (user.id, delegate.id)

    @property
    def is_active(self):
        return self.user.is_active

    def save(self):
        self.delegate.last_login = self.last_login
        self.delegate.save()

    def __str__(self):
        return str(self.user)

class DelegationAuthBackend:
    supports_object_permissions = False
    supports_anonymous_user = False

    def authenticate(self, username=None, password=None):
        try:
            if '-' in username:
                prefix, suffix = username.rsplit('-', 1)
                delegate = User.objects.get(username=username, docbowprofile__is_guest=True)
                user = User.objects.get(username=prefix)
                if delegate.check_password(password):
                    user.delegate = username
                    return DummyUser(user, delegate)
        except User.DoesNotExist:
            pass
        return None

    def get_user(self, id_pair):
        user_id, delegate_id = id_pair.rsplit(',', 1)
        try:
            user = User.objects.get(pk=user_id)
            delegate = User.objects.get(pk=delegate_id)
            user.delegate = delegate
            return user
        except User.DoesNotExist:
            return None
