# written by: Rylan Uherek, Mandeep Desai
# tested by: Rylan Uherek, Mandeep Desai
# debugged by: Rylan Uherek, Avinash Oza, Mozam Todiwala, Mandeep Desai
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.core.urlresolvers import reverse
from django import forms

from virtualstockmarket.models import *
from virtualstockmarket.SecurityInfo import *

from portfolio.models import *

# Create your views here.
def home(request):
	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_response('home.html', context)

	# render the page
	else:
		# the return list with the portfolios, their value, and the league information
		portfolios = []

		# get the user id associated with this logged in user and any associated portfolios
		user_id = request.user.id
		userleagues = LeagueUser.objects.filter(user_name=user_id)

		# loop through all of the leagues the user is in, and find their name, and the balance each user has in the league
		for i in userleagues:
			leagueidnum = i.user_league.id
			league = League.objects.get(id=leagueidnum)

			# what is the name of the league? and the end date?
			leaguename = league.league_name
			enddate = league.end_date

			# force and update of the users portfolio
			i.updateValue()

			# get the value
			currentval = i.current_value

			# add the data to the return list
			portfolios.append({'name':leaguename, 'enddate':enddate, 'value':currentval, 'id': i.id})


		return render_to_response('portfolio.html', {'portfolios' : portfolios},context)

def trade(request, leagueuser_id, portfolioentry_id = -1):
	context = RequestContext(request)
	# if the leaugeuser id is in the system, then get objects assoicated with the user or else redered an error
	leagueuser = get_object_or_404(LeagueUser, pk=leagueuser_id)
	
	
	if request.method == 'POST':
		# request the trade form and for the league_user id that requested it
		form = TradeForm(request.POST, league_user = leagueuser_id)
		# if form is valid than save or invalid form error should be returned
		if form.is_valid():
			tradeid = form.save(commit=False)

			portfolioentry = None
		
			# fill out the portfolio entries related to the league_user id with proper information, to save the trade transaction
	
			try:
				portfolioentry = PortfolioEntry.objects.get(pk=portfolioentry_id)
			except PortfolioEntry.DoesNotExist:
				portfolioentry = PortfolioEntry(user_name=leagueuser, open=1)
				portfolioentry.ticker_symbol = tradeid.ticker_symbol
				portfolioentry.quantity = tradeid.quantity
				portfolioentry.user_name = leagueuser
				portfolioentry.user_league = leagueuser.user_league
				portfolioentry.save()

			tradeid.portfolio_entry = portfolioentry
			tradeid.save()
			# if trade is buy then save entry under buy else save under sell
			if tradeid.order_action == 'BUY':
				portfolioentry.buy_entry = tradeid
			else:
				portfolioentry.sell_entry = tradeid

			portfolioentry.save()
			
			# render the portfolio home page after saving the portfolio entry
			return HttpResponseRedirect(reverse('portfolio.views.home'))
	
	else:
		# If form is invalid request the user to re-enter the trade and submit again
		form = TradeForm(league_user = leagueuser_id)

	return render_to_response('portfolio_trade.html', {'leagueuser_id' : leagueuser_id, 'form' : form}, context)

# views to display the league user detail portfolio page with transaction history

	

def detail(request,leagueuser_id):
	context= RequestContext(request)
	
	leagueuser = LeagueUser.objects.get(pk=leagueuser_id)
	leagueuser.updateValue()
	
	portfolioentries = PortfolioEntry.objects.filter(user_name=leagueuser).filter(open=1).exclude(buy_entry__order_status='PENDING')
	portfolioentries_sell = PortfolioEntry.objects.filter(user_name=leagueuser).filter(open=0).exclude(sell_entry__order_status='PENDING')
	portfolioentries_pending = PortfolioEntry.objects.filter(user_name=leagueuser).filter(buy_entry__order_status='PENDING')

	transactionhistory = PortfolioEntry.objects.filter(user_name=leagueuser).filter(open=0)	

	if request.method == 'POST':
		form = WatchlistForm(request.POST)
		if form.is_valid():
			watchlistentryid = form.save (commit=False)
			watchlistentryid.league_user = leagueuser
			watchlistentryid.save()
		else:
			print "didnt "
	else:
		form = WatchlistForm()

	

	trackstocks = WatchList.objects.filter(league_user=leagueuser)
	tracklist = []
	
	for item in trackstocks:	

		open_price = s_get_data(item.ticker_symbol,'p')
		last_price = float(s_get_data(item.ticker_symbol,'l1'))
		if open_price == 0 or last_price == 0:
			p_change = 0
		else:
			p_change = (last_price-float(open_price))/(float(open_price))
		entry = {'ticker_symbol': item.ticker_symbol, 'open_price': open_price,
'last_price': last_price,
'percent_change' : float(p_change)*100}	
		tracklist.append(entry)
		
	return render_to_response('detail.html', {'leagueuser' : leagueuser, 'portfolioentries':portfolioentries, 'portfolioentries_sell':portfolioentries_sell, 'portfolioentries_pending' : portfolioentries_pending, 'form' : form, 'tracklist':tracklist, 'leagueuser_id' : leagueuser_id}, context_instance = RequestContext(request))


		

		
	
	
