# written by: Rylan Uherek, Mozam Todiwala, Pintu Patel, Aakash Patel
# tested by: Rylan Uherek, Mozam Todiwala, Pintu Patel, Aakash Patel
# debugged by: Rylan Uherek, Avinash Oza, Mozam Todiwala, Aakash Patel
from virtualstockmarket.models import *
from league.models import *
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.core.urlresolvers import reverse
from operator import itemgetter

# if user is not logged in, then display the home page, else display the league page with all the public leagues that are active
def home(request):
	context = RequestContext(request)
	if not request.user.is_authenticated():
		return render_to_response('home.html', context)
	else:
		league_list = League.objects.all()
	return render_to_response('league.html', { 'leagues' : league_list }, context_instance= RequestContext(request))

# if user is not logged in, then display the homepage, else take the user to league create form page
def create_league(request):
	context = RequestContext(request)
	if not request.user.is_authenticated():
		return render_to_response('home.html', context)
	# post method will post data inputted into form
	if request.method == 'POST':
		form = LeagueForm(request.POST)
		if form.is_valid():
			# save the league information in the database
			league = form.save(commit=False)
			league.league_admin = User.objects.get(pk=request.user.id)
			league.save()
			# associate the league with the league user that created the league
			newuser = LeagueUser(user_name=request.user, cash_balance=form.cleaned_data['starting_balance'], current_value=form.cleaned_data['starting_balance'], user_league=league)
			newuser.save() 
			
			#return render_to_response('league.html',{ 'user' : user }, context_instance= RequestContext(request))
			return HttpResponseRedirect(reverse('league.views.home', args =()))	
		
		return HttpResponse("nogood")
	else:
		# return the old form and any errors
		form = LeagueForm()
	variables = RequestContext(request, {
        	'form': form
    	})
	return render_to_response('create_league.html',context, variables)

# if user is not logged in, then display the homepage, else display the detail information page about each league
def league_info(request,league_id):
	
	context = RequestContext(request)
	if not request.user.is_authenticated():
		return render_to_response('home.html', context)
	
	else:
		# get all the attributes related to the league associated with the league id
		league = League.objects.get(pk=league_id)
		# get the users associated with the league id
		users = LeagueUser.objects.filter(user_league=league_id)
		alreadyjoined = LeagueUser.objects.filter(user_name=request.user).filter(user_league=league)
		
		#there needs to be a bool check to see if a user already exist in the league somehow.
		user_id = request.user.id
		userInLeague = LeagueUser.objects.filter(user_league=league_id).filter(user_name=user_id).count()

		# check if the user is the admin
		isAdmin = 0
		if league.league_admin == request.user:
			isAdmin = 1
				
		if (league.private is True) and (userInLeague is 1):
			return render_to_response('league_info.html',{ 'league' : league, 'users' : users, 'showjoin': alreadyjoined, 'isAdmin':isAdmin }, context_instance= RequestContext(request))
		elif league.private is True:
			return render_to_response('league_info.html', {'showjoin': 1, 'hidetable':1, 'privatejoinshow' :1, 'league' : league }, context)
		else:
			return render_to_response('league_info.html',{ 'league' : league, 'users' : users, 'showjoin': alreadyjoined, 'isAdmin':isAdmin }, context_instance= RequestContext(request))

# join a league		
def join(request):
	context = RequestContext(request)
	if request.method == 'POST':
		# get the leaggue id, for the league that join league request is processed 
		league = League.objects.get(pk = request.POST['leagueId'])
		# associate the leauge with the requested user that joined the league and save information about new user and display league information page
		if league.private is False:
			newuser = LeagueUser(user_name=request.user, cash_balance=league.starting_balance, current_value=league.starting_balance, user_league=league)
			newuser.save() 
			return HttpResponseRedirect(reverse('league.views.league_info', args =(league.id,)))
		else:
			password = request.POST['password']
			league_password = League.objects.get(pk = request.POST['leagueId']).league_password

			if password == league_password:
				newuser = LeagueUser(user_name=request.user, cash_balance=league.starting_balance, current_value=league.starting_balance, user_league=league)
				newuser.save() 
				return HttpResponseRedirect(reverse('league.views.league_info', args =(league.id,)))
			else:
				return HttpResponse('invalid password')

	return HttpResponse('an error has occured')

def adminpanel(request,league_id):
	league = League.objects.get(pk = league_id)
	usersInLeague = LeagueUser.objects.filter(user_league=league)

	if league.league_admin != request.user:
		return HttpResponse('you are not the admin')
	else:
		return render_to_response('league_admin.html', {'league':league, 'usersInLeague':usersInLeague} ,context_instance= RequestContext(request))

def kick(request):
	context = RequestContext(request)

	if request.method == 'POST':
		league = League.objects.get(pk = request.POST['leagueId'])
		leagueUser = LeagueUser.objects.get(pk = request.POST['leagueUser'])
		
		if league.league_admin == request.user:
			leagueUser.delete()
			usersInLeague = LeagueUser.objects.filter(user_league=league)
			return render_to_response('league_admin.html', {'league':league, 'usersInLeague':usersInLeague} ,context_instance= RequestContext(request))
		else:
			return HttpResponse('you are not the admin')
	else:
		return HttpResponse('an error has occurred')

#League ranking method
def league_ranking(request,league_id):
	context = RequestContext(request)

	# only display this page to a registered and authenticated user
	# otherwise send them back to the home page
	if not request.user.is_authenticated():
		return render_to_reponse('home.html', context)
	else: 
		#ranking for each user in the league	
		ranking = []

		userleagues = League.objects.get(pk=league_id)
		league = LeagueUser.objects.filter(user_league=league_id)
		leaguename = userleagues.league_name
		
		for i in league:
			
			i.updateValue()
			currentvalue = float(i.current_value)
			startbalance = float(userleagues.starting_balance)
			
			percentgain = ((currentvalue-startbalance)/startbalance)*100
			#create a directory of the attributes for each user
			entry={'username':i.user_name,'leaguename':userleagues.league_name,'currentvalue':currentvalue,'percentgain':percentgain}
			
			ranking.append(entry)
			#order the list
			newlist = sorted(ranking, key=itemgetter('percentgain'),reverse=True) 
				
	return render_to_response('ranking.html',{'ranking': ranking,'newlist': newlist}, context_instance=RequestContext(request))

