# written by: Avinash  Oza
# tested by: Avinash Oza
# debugged by: Avinash Oza

from django.core.management.base import BaseCommand, CommandError
from virtualstockmarket.models import *
from virtualstockmarket.SecurityInfo import *

class Command(BaseCommand):
	args = ''
	help = 'Changes the status of current pending orders'
	
	def handle(self, *args, **options):
			#Get all orders which are currently pending
			all_orders = TicketEntry.objects.filter(order_status = 'PENDING').order_by('ticker_symbol')
			self.stdout.write('Total number of pending orders: %s \n' % all_orders.count())
	
			for order in all_orders: #Process order by order
				user_cash = order.portfolio_entry.user_name #Current League User object 

				curr_price = s_get_data(order.ticker_symbol,'l1')
				
				if float(curr_price) < 0.01:
					#Case where symbol doesn't exist
					order.order_status = 'CANCELLED'
					order.execution_price = 0
					order.save()				
					self.stdout.write('Invalid ticker symbol ')
					self.stdout.write(order.ticker_symbol)
					self.stdout.write(' detected. Cancelling order.\n')
					continue
				#self.stdout.write(curr_price)
				if order.order_type == 'LIMIT': #Process limit orders
					if float(order.limit_price) > float(curr_price) and order.order_action == 'BUY' and ((float(limit_price)*float(order.quantity)) < user_cash.cash_balance):
						#limit order was met since their lowest was higher than current and they want to buy
						self.stdout.write('Processed a long limit order\n')
						order.order_status = 'COMPLETED'
						order.execution_price = float(curr_price)
						order.save()

						user_cash.cash_balance = float(user_cash.cash_balance) - float(curr_price)*float(order.quantity)
						user_cash.save()

					elif float(order.limit_price) < float(curr_price) and order.order_action == 'SELL' :
						self.stdout.write('Processed a sell limit order\n')
						order.order_status = 'COMPLETED'
						order.execution_price = float(curr_price)
						order.save()

						user_cash.cash_balance = user_cash.cash_balance + float(curr_price)*float(order.quantity)
						user_cash.save()
					else:
						self.stdout.write('Did not process this limit order (Limit price may have not been met, not enough cash, etc.) \n')


				elif order.order_type =='MARKET': # Process a market order
					#Most risky type of order, can get filled at any price.
					if order.order_action == 'BUY' and ((float(curr_price)*float(order.quantity)) < user_cash.cash_balance):
					#User can afford current price
						order.order_status = 'COMPLETED'
						order.execution_price = float(curr_price)
						order.save()

						user_cash.cash_balance = float(user_cash.cash_balance) - float(curr_price)*float(order.quantity)
						user_cash.save()
						self.stdout.write('Processed a long market order\n')
					elif order.order_action == 'SELL': #No special conditions to sell

						order.order_status = 'COMPLETED'
						order.execution_price = float(curr_price)
						order.save()
						
						user_cash.cash_balance = float(user_cash.cash_balance) + float(curr_price)*float(order.quantity)
						user_cash.save()
						self.stdout.write('Processed a short market order\n')
					else:
						self.stdout.write('Unprocessed market order. May not have enough cash to buy. \n')

				#Book keeping stuff to update the portfolio entry so it is rendered correctly and to clear some flags
				#If the entries exist for buy and sell and are both completed,the trade is considered closed
				portfolio_entry = order.portfolio_entry
				if portfolio_entry.buy_entry and portfolio_entry.sell_entry and portfolio_entry.buy_entry.order_status == 'COMPLETED' and portfolio_entry.sell_entry.order_status == 'COMPLETED':
					portfolio_entry.open = 0
					portfolio_entry.save()
			
