from django.template import Context, loader
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from django.contrib.auth import logout as auth_logout
from django.contrib.auth import login as auth_login
from django import forms

from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse

from registration import RegistrationForm


from datetime import datetime
from django.utils.timezone import utc
from calendar import monthrange
import calendar

def home(request):
	context = RequestContext(request)
	return render_to_response('home.html', context)

# register view
def register(request):
	context = RequestContext(request)
	newForm = RegistrationForm()

	if request.POST:
		form = RegistrationForm(request.POST)
		if form.is_valid():
			new_user = form.create_user()
			
						
			return render_to_response('home.html', context)
		else:
			# return the old form and any errors
			newForm = form
	
	return render_to_response('register.html', {'form':newForm} , context)


# login view
def login(request):
	context = RequestContext(request)
	if request.method == "POST":
		username = request.POST.get('username')
		password = request.POST.get('pass')

		# attempt to authenticate the username and password
		user = authenticate(username=username, password=password)
		error = ""

		if not (username and password):
			error = "ERROR: One or more of the fields is blank."
		elif user is None:
			error = "ERROR: Sorry, the login you provided was invalid."
		elif not user.is_active:
			error = "ERROR: Sorry, your account is inactive."
		else:
			auth_login(request, user)

		# handle an error
		if error:
			c = RequestContext(request, {'state':error})
			return render_to_response('home.html', c)
		else:
			# reverse to the portfolio
			return HttpResponseRedirect(reverse('portfolio.views.home'))

	return render_to_response('home.html', context)

def logout(request):
	auth_logout(request)
	return HttpResponseRedirect(reverse('home'))

def about_us(request):
	context = RequestContext(request)
	return render_to_response('about_us.html', context)

def faq(request):
	context = RequestContext(request)
	return render_to_response('faq.html', context)
