from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.shortcuts import render
from django.urls import reverse
from django.http import HttpResponseRedirect, HttpResponse

from django.utils import timezone

from olaf.models import *
from olaf.forms import *
from olaf.utility import usertools

from olaf.chess.controller import proccess_move

def index ( request ):
	args = {}

	message = request.session.pop ( 'message', default = None )
	if ( message is not None ):
		args [ 'message' ] = message

	if ( request.user.is_authenticated ):
		if ( request.method == 'POST' ):
			if ( request.POST.get ( 'game_id' ) is not None ):
				game_id = request.POST.get ( 'game_id' )
				if ( game_id == '-1' ):
					game_id = usertools.new_game ( request )

				request.session [ 'game_id' ] = game_id
			else:
				request.session.pop ( 'game_id', default = None )

		f = lambda a : str ( a.date () ) + " - " + str ( a.hour ) + ":" + str ( a.minute ) + ":" + str ( a.second )
		args [ 'game_list' ] = list ([str ( game.id ), f ( game.creation_time )] for game in request.user.userdata.game_history.filter ( result = 0 ).order_by ( '-creation_time' ) )

		if ( request.session.get ( 'game_id' ) is not None ):
			args [ 'game_board' ] = usertools.get_translated_game_board ( request )
		else:
			args [ 'game_board' ] = None

		return render ( request, 'olaf/index_logged_in.html', args )
	else:
		args [ 'login_form' ] = LoginForm ()
		args [ 'register_form' ] = RegisterForm ()
		args [ 'score' ] = list ( [user.master.username, user.wins, user.loses, user.ties] for user in UserData.objects.filter ( is_active = True ) )

		return render ( request, 'olaf/index_not_logged_in.html', args )

form_operation_dict = {
	'login' : (
		usertools.login_user,
		LoginForm,
		'olaf/login.html',
		{},
		'index',
		{ 'message' : "You're logged in. :)"}
	),
	'register' : (
		usertools.register_user,
		RegisterForm,
		'olaf/register.html',
		{},
		'index',
		{ 'message' : "An activation email has been sent to you" }
	),
	'password_reset_request' : (
		usertools.init_pass_reset_token,
		ForgotPasswordUsernameOrEmailForm,
		'olaf/password_reset_request.html',
		{},
		'index',
		{ 'message' : "An email containing the password reset link will be sent to your email"}
	),
	'reset_password' : (
		usertools.reset_password_action,
		PasswordChangeForm,
		'olaf/reset_password.html',
		{},
		'olaf:login',
		{ 'message' : "Password successfully changed, you can login now" }
	),
	'resend_activation_email' : (
		usertools.resend_activation_email,
		ResendActivationUsernameOrEmailForm,
		'olaf/resend_activation_email.html',
		{},
		'index',
		{ 'message' : "Activation email successfully sent to your email" }
	),
}
def form_operation ( request, oper, *args ):
	func, FORM, fail_template, fail_args, success_url, success_args = form_operation_dict [ oper ]

	if ( request.method == 'POST' ):
		form = FORM ( request.POST )

		if ( form.is_valid () ):
			func ( request, form, *args )

			for key in success_args:
				request.session [ key ] = success_args [ key ]
			return HttpResponseRedirect ( reverse ( success_url ) )
	else:
		form = FORM ()

	message = request.session.pop ( 'message', default = None )
	if ( message is not None ):
		fail_args [ 'message' ] = message

	fail_args [ 'form' ] = form
	return render ( request, fail_template, fail_args )

#view functions

def login_user ( request ):
	if ( request.user.is_authenticated ):
		return HttpResponseRedirect ( reverse ( 'index' ) )

	return form_operation ( request, 'login' )

def register_user ( request ):
	if ( request.user.is_authenticated ):
		return HttpResponseRedirect ( reverse ( 'index' ) )

	return form_operation ( request, 'register' )

def password_reset_request ( request ):
	if ( request.user.is_authenticated ):
		return HttpResponseRedirect ( reverse ( 'index' ) )

	return form_operation ( request, 'password_reset_request' )

def reset_password_action ( request, token ):
	if ( request.user.is_authenticated ):
		return HttpResponseRedirect ( reverse ( 'index' ) )

	tk = ExpirableTokenField.objects.filter ( token = token ).first ()
	if ( tk is None ):
		request.session [ 'message' ] = "Broken link"
		return HttpResponseRedirect ( reverse ( 'index' ) )
	else:
		if ( timezone.now () <= tk.expiration_time ):
			return form_operation ( request, 'reset_password', token )
		else:
			request.session [ 'message' ] = "Link expired, try getting a new one"
			return HttpResponseRedirect ( reverse ( 'olaf:reset_password' ) )

def activate_account ( request, token ):
	if ( request.user.is_authenticated ):
		return HttpResponseRedirect ( reverse ( 'index' ) )

	tk = ExpirableTokenField.objects.filter ( token = token ).first ()
	if ( tk is None ):
		request.session [ 'message' ] = "Broken link"
		return HttpResponseRedirect ( reverse ( 'index' ) )
	else:
		if ( timezone.now () <= tk.expiration_time ):
			if ( tk.user.is_active ):
				request.session [ 'message' ] = "Account already active"
				return HttpResponseRedirect ( reverse ( 'index' ) )
			else:
				userdata = tk.user
				userdata.is_active = True
				userdata.save ()

				request.session [ 'message' ] = "Your account has been activated successfully"
				return HttpResponseRedirect ( reverse ( 'olaf:login' ) )
		else:
			request.session [ 'message' ] = "Link expired, try getting a new one"
			return HttpResponseRedirect ( reverse ( 'olaf:resend_activation_email' ) )

def resend_activation_email ( request ):
	if ( request.user.is_authenticated ):
		return HttpResponseRedirect ( reverse ( 'index' ) )

	return form_operation ( request, 'resend_activation_email' )

def logout_user ( request ):
	usertools.logout_user ( request )

	request.session [ 'message' ] = "Goodbye :)"
	return HttpResponseRedirect ( reverse ( 'index' ) )

def scoreboard ( request ):
	if ( request.method == 'POST' ):
		username = request.POST.get ( 'username' )
		user = User.objects.filter ( username = username ).first ()

		if ( user is None ):
			request.session [ 'message' ] = "User not found"
			return HttpResponseRedirect ( reverse ( 'olaf:scoreboard' ) )
		else:
			return HttpResponseRedirect ( reverse ( 'olaf:user_profile', args = (username, ) ) )
	else:
		args = {}

		message = request.session.pop ( 'message', default = None )
		if ( message is not None ):
			args [ 'message' ] = message

		lst = [ (user.master.username, user.wins, user.loses, user.ties) for user in UserData.objects.filter ( is_active = True ) ]
		args [ 'lst' ] = lst

		if ( request.user.is_authenticated ):
			args [ 'logged_in' ] = True

		return render ( request, 'olaf/scoreboard.html', args )

def move ( request ):
	proccess_move ( request )

	return HttpResponseRedirect ( reverse ( 'index' ) )
[((111, 8, 111, 52), 'django.shortcuts.render', 'render', ({(111, 17, 111, 24): 'request', (111, 26, 111, 39): 'fail_template', (111, 41, 111, 50): 'fail_args'}, {}), '(request, fail_template, fail_args)', False, 'from django.shortcuts import render\n'), ((179, 1, 179, 34), 'olaf.utility.usertools.logout_user', 'usertools.logout_user', ({(179, 25, 179, 32): 'request'}, {}), '(request)', False, 'from olaf.utility import usertools\n'), ((210, 1, 210, 26), 'olaf.chess.controller.proccess_move', 'proccess_move', ({(210, 17, 210, 24): 'request'}, {}), '(request)', False, 'from olaf.chess.controller import proccess_move\n'), ((41, 9, 41, 62), 'django.shortcuts.render', 'render', ({(41, 18, 41, 25): 'request', (41, 27, 41, 54): '"""olaf/index_logged_in.html"""', (41, 56, 41, 60): 'args'}, {}), "(request, 'olaf/index_logged_in.html', args)", False, 'from django.shortcuts import render\n'), ((47, 9, 47, 66), 'django.shortcuts.render', 'render', ({(47, 18, 47, 25): 'request', (47, 27, 47, 58): '"""olaf/index_not_logged_in.html"""', (47, 60, 47, 64): 'args'}, {}), "(request, 'olaf/index_not_logged_in.html', args)", False, 'from django.shortcuts import render\n'), ((182, 31, 182, 50), 'django.urls.reverse', 'reverse', ({(182, 41, 182, 48): '"""index"""'}, {}), "('index')", False, 'from django.urls import reverse\n'), ((207, 9, 207, 57), 'django.shortcuts.render', 'render', ({(207, 18, 207, 25): 'request', (207, 27, 207, 49): '"""olaf/scoreboard.html"""', (207, 51, 207, 55): 'args'}, {}), "(request, 'olaf/scoreboard.html', args)", False, 'from django.shortcuts import render\n'), ((212, 31, 212, 50), 'django.urls.reverse', 'reverse', ({(212, 41, 212, 48): '"""index"""'}, {}), "('index')", False, 'from django.urls import reverse\n'), ((37, 27, 37, 74), 'olaf.utility.usertools.get_translated_game_board', 'usertools.get_translated_game_board', ({(37, 65, 37, 72): 'request'}, {}), '(request)', False, 'from olaf.utility import usertools\n'), ((117, 32, 117, 51), 'django.urls.reverse', 'reverse', ({(117, 42, 117, 49): '"""index"""'}, {}), "('index')", False, 'from django.urls import reverse\n'), ((123, 32, 123, 51), 'django.urls.reverse', 'reverse', ({(123, 42, 123, 49): '"""index"""'}, {}), "('index')", False, 'from django.urls import reverse\n'), ((129, 32, 129, 51), 'django.urls.reverse', 'reverse', ({(129, 42, 129, 49): '"""index"""'}, {}), "('index')", False, 'from django.urls import reverse\n'), ((135, 32, 135, 51), 'django.urls.reverse', 'reverse', ({(135, 42, 135, 49): '"""index"""'}, {}), "('index')", False, 'from django.urls import reverse\n'), ((140, 32, 140, 51), 'django.urls.reverse', 'reverse', ({(140, 42, 140, 49): '"""index"""'}, {}), "('index')", False, 'from django.urls import reverse\n'), ((142, 7, 142, 22), 'django.utils.timezone.now', 'timezone.now', ({}, {}), '()', False, 'from django.utils import timezone\n'), ((150, 32, 150, 51), 'django.urls.reverse', 'reverse', ({(150, 42, 150, 49): '"""index"""'}, {}), "('index')", False, 'from django.urls import reverse\n'), ((155, 32, 155, 51), 'django.urls.reverse', 'reverse', ({(155, 42, 155, 49): '"""index"""'}, {}), "('index')", False, 'from django.urls import reverse\n'), ((157, 7, 157, 22), 'django.utils.timezone.now', 'timezone.now', ({}, {}), '()', False, 'from django.utils import timezone\n'), ((174, 32, 174, 51), 'django.urls.reverse', 'reverse', ({(174, 42, 174, 49): '"""index"""'}, {}), "('index')", False, 'from django.urls import reverse\n'), ((102, 33, 102, 56), 'django.urls.reverse', 'reverse', ({(102, 43, 102, 54): 'success_url'}, {}), '(success_url)', False, 'from django.urls import reverse\n'), ((146, 33, 146, 66), 'django.urls.reverse', 'reverse', ({(146, 43, 146, 64): '"""olaf:reset_password"""'}, {}), "('olaf:reset_password')", False, 'from django.urls import reverse\n'), ((170, 33, 170, 75), 'django.urls.reverse', 'reverse', ({(170, 43, 170, 73): '"""olaf:resend_activation_email"""'}, {}), "('olaf:resend_activation_email')", False, 'from django.urls import reverse\n'), ((187, 9, 187, 52), 'django.contrib.auth.models.User.objects.filter', 'User.objects.filter', (), '', False, 'from django.contrib.auth.models import User\n'), ((191, 33, 191, 62), 'django.urls.reverse', 'reverse', ({(191, 43, 191, 60): '"""olaf:scoreboard"""'}, {}), "('olaf:scoreboard')", False, 'from django.urls import reverse\n'), ((193, 33, 193, 85), 'django.urls.reverse', 'reverse', (), '', False, 'from django.urls import reverse\n'), ((27, 15, 27, 45), 'olaf.utility.usertools.new_game', 'usertools.new_game', ({(27, 36, 27, 43): 'request'}, {}), '(request)', False, 'from olaf.utility import usertools\n'), ((160, 34, 160, 53), 'django.urls.reverse', 'reverse', ({(160, 44, 160, 51): '"""index"""'}, {}), "('index')", False, 'from django.urls import reverse\n'), ((167, 34, 167, 58), 'django.urls.reverse', 'reverse', ({(167, 44, 167, 56): '"""olaf:login"""'}, {}), "('olaf:login')", False, 'from django.urls import reverse\n')]