# written by: Rylan Uherek, Mandeep Desai
# tested by: Rylan Uherek, Mandeep Desai
# debugged by: Avinash Oza, Mozam Todiwala, Mandeep Desai
from django.db import models
from django.forms import ModelForm
from django import forms

from virtualstockmarket.models import *



class TradeForm(ModelForm):

	def clean(self):
		cleaned_data = super(TradeForm,self).clean()
		
		l_user = LeagueUser.objects.get(pk=self.league_user) #Get the user's entry
		
		#Calculate cash value of the trade
		limit_price = cleaned_data.get("limit_price")
		quantity = cleaned_data.get("quantity")
		order_type = cleaned_data.get("order_type")
		quantity = cleaned_data.get("quantity")

		#VALIDATION SECTION FOR DIFFERENT TRADE TYPES

		if order_type != "MARKET" and not limit_price:
			raise forms.ValidationError("A limit price needs to be defined for any order type aside from Market")

		if limit_price and quantity:
			trade_value = limit_price * quantity
			if (l_user.cash_balance - trade_value) < 0:
				#Good
				raise forms.ValidationError("You don't have enough cash for this transaction")	
		
		if quantity < 1:
			raise forms.ValidationError("The quantity of shares needs to be greater than 1")
		return cleaned_data

	def __init__(self, *args, **kwargs):
                self.league_user = kwargs.pop('league_user')
                super(TradeForm, self).__init__(*args, **kwargs)

	class Meta:
		model = TicketEntry
		exclude = ('portfolio_entry', 'date_added', 'execution_price', 'stop_reached','date_executed', 'order_status')



# added a new class for WatchList
class WatchList (models.Model):
	league_user = models.ForeignKey(LeagueUser, blank=True, related_name = 'UserNameWL', null=True )

	ticker_symbol = models.CharField (max_length=8, db_column='WLTickerSymbol')	
	
	def __unicode__(self):
		return self.user_name, self.ticker_symbol, self.track_price

class WatchlistForm(ModelForm):

	class Meta:
		model = WatchList
		exclude = ('league_user')


		
