from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import PasswordChangeForm
from django.core.urlresolvers import reverse
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 _
from forms import ProfileChangeForm


    
@login_required   
def profile(request):
    if request.method == "POST":
        form = ProfileChangeForm(request.user, request.POST)
        
        if form.is_valid():
            form.save()
            form = None
    else:
        form = ProfileChangeForm()
    return render_to_response('ldt/user/change_profile.html', {'form' : form }, context_instance=RequestContext(request))    

    
def logout_view(request):
    logout(request)
    return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
    #return HttpResponseRedirect(settings.LOGOUT_URL)

    
def loginAjax(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))

               
@login_required   
def password(request):
    if request.method == "POST":
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            form.save()
            form = None
    else:
        form = PasswordChangeForm(request.user)
    return render_to_response('ldt/user/change_password.html', {'form': form, }, context_instance=RequestContext(request))


@login_required   
def language(request):
    return render_to_response('ldt/user/change_language.html', { 'url_change_language' : reverse('django.views.i18n.set_language')}, context_instance=RequestContext(request))
