from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext, loader
from django.utils import simplejson
from django.utils.translation import ugettext as _
    

def logout_view(request):
    logout(request)
    return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
    #return HttpResponseRedirect(settings.LOGOUT_URL)
    
def login_ajax(request, loginstate_template_name='ldt/user/login_form.html'):
    if request.method == "POST":
        username = request.POST["username"]
        password = request.POST["password"]
        user = authenticate(username=username, password=password)
        error_message = _(u"Sorry, that's not a valid username or password.")
        if user is not None:
            if user.is_active:
                login(request, user)
                context = RequestContext(request, { 'username': user.username, })
                template = loader.get_template(loginstate_template_name)
                html = template.render(context)
                return HttpResponse(simplejson.dumps({'message': u'successful', 'username': user.username, 'html': html, 'reload': request.POST["reload"], }))               
            else:
                return HttpResponse(simplejson.dumps({'message': error_message, }))
        else:
            return HttpResponse(simplejson.dumps({'message': error_message, }))
    return render_to_response('ldt/user/login_ajax.html', context_instance=RequestContext(request))

               
