from django.contrib.auth.decorators import user_passes_test
from django.contrib.auth.views import redirect_to_login
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import redirect
from django.urls.base import reverse
from og_django_utils.utils.decorators import class_view_decorator


def require_apprentice(view_func):
    def wrapped(request, *args, **kwargs):
        if request.user.is_anonymous():
            path = request.build_absolute_uri()
            return redirect_to_login(path, reverse_lazy('users:login'))
        else:
            if not getattr(request.user, 'has_admin_access', True):
                return redirect(reverse('admin:index'))
            return view_func(request, *args, **kwargs)
    return wrapped


require_anonymous = user_passes_test(lambda u: not u.is_authenticated(), reverse_lazy('path-list'))
anonymous_required = class_view_decorator(require_anonymous)

# Class decorator requiring Apprentice login
apprentice_login_required = class_view_decorator(require_apprentice)

# Method decorator requiring SUPER_USER login
super_user_login_required = user_passes_test((lambda u: u.is_superuser), reverse_lazy('admin:login'))

# Class decorator requiring SUPER_USER login
require_super_user_login = class_view_decorator(super_user_login_required)
