# written by: Avinash Oza, Mozam Todiwala
# tested by: Avinash Oza, Mozam Todiwala
# debugged by: Avinash Oza, Mozam Todiwala

# code is based on Huxley from K. Mehta (https://github.com/kmeht/huxley/)
# all credit to him for his awesome registration system

from django import forms
from django.contrib.auth.models import User
from models import *

from datetime import date
import re

class RegistrationForm(forms.Form):
	#User information
	FirstName = forms.CharField(label="First Name:", widget=forms.TextInput(attrs={'class':'required input_field'}))
	LastName = forms.CharField(label="Last Name:", widget=forms.TextInput(attrs={'class':'required input_field'}))

	Username = forms.CharField(label="Username:", widget=forms.TextInput(attrs={'class':'required input_field'}))
	Password = forms.CharField(label="Password:", widget=forms.PasswordInput(attrs={'class':'required input_field'}))
	Email = forms.CharField(label="E-Mail Address:", widget=forms.TextInput(attrs={'class':'required input_field'}))
	ConfirmEmail = forms.CharField(label="Confirm E-Mail Address:", widget=forms.TextInput(attrs={'class':'required input_field'}))	

	# ===== DB Functions =============================================================================
	#  run these only if form is valid

	def create_user(self):
		try:
			new_user = User.objects.create_user(self.cleaned_data['Username'], self.cleaned_data['Email'], self.cleaned_data['Password'])
			new_user.first_name = self.cleaned_data['FirstName']
			new_user.last_name = self.cleaned_data['LastName']
			new_user.save()
			return new_user
		except:
			print "> ERROR: Could not create a user."
			return None

	# ===== Validation =============================================================================
	def clean_Username(self):
		# check for uniqueness
		username = self.cleaned_data['Username']
		user_exists = User.objects.filter(username=username).exists()
		if user_exists:
			raise forms.ValidationError("Username '%s' is already in use. Please choose another one." % (username))
		if re.match("^[A-Za-z0-9\_\-]+$", username) is None:
			raise forms.ValidationError("Usernames must be alphanumeric, underscores, and/or hyphens only.")

		# return data, changed or not
		return username

	def clean_Password(self):
		password = self.cleaned_data['Password']
		if re.match("^[A-Za-z0-9\_\.!@#\$%\^&\*\(\)~\-=\+`\?]+$", password) is None:
			raise forms.ValidationError("Password contains invalid characters.")
		return password

	# general clean method
	def clean(self):
		cleaned_data = super(RegistrationForm, self).clean()

		return cleaned_data

