from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import InputRequired, Length, EqualTo, ValidationError
from passlib.hash import pbkdf2_sha256
from models import User

def invalid_credentials(form, field):
	''' Username and password checker '''

	username_entered = form.username.data
	password_entered = field.data

	user_object = User.query.filter_by(username=username_entered).first()
	if user_object is None:
		raise ValidationError("Username or password is incorrect")
	elif not pbkdf2_sha256.verify(password_entered, user_object.password):
		raise ValidationError("Username or password is incorrect")

class JoinRoomForm(FlaskForm):
	room_code = StringField('room_code', validators=[InputRequired(message="Room Code Required")])
	username = StringField('username', validators=[InputRequired(message="Username Required")])
	# room_code = StringField('room_code')
	# username = StringField('username')
	submit_button = SubmitField('Join Room')
class CreateRoomForm(FlaskForm):
	username = StringField('username', validators=[InputRequired(message="Username Required")])
	numplayers = StringField('numplayers', validators=[InputRequired(message="Username Required")])
	# room_code = StringField('room_code')
	# username = StringField('username')
	submit_button = SubmitField('Join Room')

class CreateUsernameForm(FlaskForm):
	username = StringField('username', validators=[InputRequired(message="Username Required")])
	# room_code = StringField('room_code')
	# username = StringField('username')
	submit_button = SubmitField('Join Room')

class RegistrationForm(FlaskForm):
	''' Registration form '''

	username = StringField('username_label', validators=[InputRequired(message="Username required"),
		Length(min=4, max=25, message="Username must be between 4 and 25 characters")])
	password = PasswordField('password_label', validators=[InputRequired(message="Password required"),
		Length(min=4, message="Password must be at least 4 characters")])
	confirm_pswd = PasswordField('confirm_pswd_label', validators=[InputRequired(message="Please retype your password"),
		EqualTo('password', message="Passwords must match")])
	submit_button = SubmitField('Click Here to Start')

	def validate_username(self, username):
		user_object = User.query.filter_by(username=username.data).first()
		if user_object:
			raise ValidationError("Username already exists. Select a different username")


class LoginForm(FlaskForm):
	''' Login form '''

	username = StringField('username_label', validators=[InputRequired(message="Username required")])
	password = PasswordField('password_label', validators=[InputRequired(message="Password required"), invalid_credentials])
	submit_button = SubmitField('Login')
