from django.utils.http import is_safe_url
from django.contrib.auth import authenticate, login, logout, get_user_model
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import redirect, render, HttpResponseRedirect
from django.core.urlresolvers import reverse_lazy
from django.contrib.auth.forms import AuthenticationForm
from django.views.generic import FormView
from django.views.generic.base import RedirectView, TemplateView
from django.views.generic.edit import CreateView

User = get_user_model()

def login_form(request):
	pass

def login_view(request):
	return HttpResponse('show show a login form')
	
def logout_view(request):
	logout(request)


class LoginView(FormView):
	template_name = "registration/login.html"
	form_class = AuthenticationForm
	success_url = reverse_lazy('home')
	redirect_field_name = "next"
	
	def get_context_data(self, **kwargs):
		context = super(LoginView, self).get_context_data(**kwargs)
		context["next"] = self.get_success_url()
		return context
	
	def get(self, request, *args, **kwargs):
		if request.user.is_authenticated():
			return HttpResponseRedirect(self.get_success_url())
		return super(LoginView, self).get(request, *args, **kwargs)
	
	def form_valid(self, form):
		login(self.request, form.get_user())
		return HttpResponseRedirect(self.get_success_url())
	
	def get_success_url(self):
		redirect_to = self.request.POST.get(self.redirect_field_name, self.request.GET.get(self.redirect_field_name, self.success_url))
		return redirect_to

class LogoutView(RedirectView):
	url = reverse_lazy("home")
	
	def get(self, request, *args, **kwargs):
		logout(request)
		return super(LogoutView, self).get(request, *args, **kwargs)
	
class RegisterView(CreateView):
	model = User 
	template_name = 'registration/register.html'
	form_class = UserCreationForm
	success_url = reverse_lazy("account:user_created")
	
	def post(self, request, *args, **kwargs):
		self.object = None
		form = self.get_form()
		if form.is_valid():
			form.save()
			user = authenticate(username=request.POST["username"], password=request.POST["password1"])
			login(request, user)
			return HttpResponseRedirect(self.success_url)
		else:
			return self.form_invalid(form)

class UserCreatedView(TemplateView):
	template_name='registration/created.html'