from django.contrib.auth import authenticate
from django.contrib.auth.forms import SetPasswordForm
from django.shortcuts import render
from django.contrib import messages
from django.utils.translation import ugettext as _

from auf.django.secretquestions.decorators import secret_questions_required
from auf.django.secretquestions.views import setup_form


from authentic2.utils import login, continue_to_next_url
from authentic2.decorators import setting_enabled


from . import app_settings

__ALL__ = [ 'lost_password_login', 'secret_questions' ]

@setting_enabled('ENABLE', settings=app_settings)
@secret_questions_required(60)
def lost_password_login(request):
    user = authenticate(user=request.secret_questions_user)
    return login(request, user, 'secret-questions')

@setting_enabled('ENABLE', settings=app_settings)
@secret_questions_required(6000)
def lost_password_reset(request):
    user = authenticate(user=request.secret_questions_user)
    if request.method == 'POST':
        if 'cancel' in request.POST:
            return continue_to_next_url(request, keep_params=False)
        form = SetPasswordForm(data=request.POST,
                user=user)
        if form.is_valid():
            form.save()
            messages.info(request, _('Your password has been reset, please login'))
            return continue_to_next_url(request, keep_params=False)
    else:
        form = SetPasswordForm(user=user)
    return render(request, 'authentic2_auf/reset_password.html', {'form': form})


secret_questions = setup_form
