def rankings():
	dict = db.rankings()
	ranks = {}
	if "logged_in" in session:
		for username in dict:
			stock_data = db.get_stocks(username)
			counter = 0
			for each in stock_data:
				data = db.get_portfolio(username)
				stock_info = info.getStocks(each[0])
				if (counter == 0):
					buying_power = data[2]
				else:
					buying_power = data[1]
				new_account_val = buying_power + round(stock_info["latestPrice"] * int(each[1]), 2)
				print(new_account_val)
				value = round((new_account_val / 100000.00) - 1.00, 2)
				counter = counter + 1
				db.add_profile(username,round(new_account_val, 2), data[2], data[3], value)
			data = db.get_portfolio(username)
		data = db.get_portfolio(session["logged_in"])
		i = 1;
		for username in dict:
			ranks[i] = [username, dict[username]]
			i = i + 1
		return render_template("rankings.html", portfolio_data = data, order = ranks, user = session["logged_in"] ,title = "Rankings", heading = "Rankings", logged_in = True)
	else:
		flash("Please login to view Rankings")
		return render_template("login.html", title = "Login", heading = "Login", type = "rankings")
def portfolio():
	if "logged_in" in session:
		stock_data = db.get_stocks(session["logged_in"])
		print("stock data : " )
		print(stock_data)
		counter = 0;
		for each in stock_data:
			data = db.get_portfolio(session["logged_in"])
			stock_info = info.getStocks(each[0])
			stock_data[counter] = [each[0], each[1], each[2], stock_info["latestPrice"], round(stock_info["latestPrice"] * int(each[1]), 2), stock_info["companyName"]]
			print(stock_data)
			if (counter == 0):
				buying_power = data[2]
			else:
				buying_power = data[1]
			new_account_val = buying_power + stock_data[counter][4]
			print(new_account_val)
			value = round((new_account_val / 100000.0) - 1.00, 2)
			print(value)
			counter = counter + 1
			db.add_profile(session["logged_in"],round(new_account_val, 2), data[2], data[3], value)
		data = db.get_portfolio(session["logged_in"])
		return render_template("portfolio.html", title = "Portfolio", heading = "Portfolio", portfolio_data = data, bought_stocks = stock_data, logged_in = True)
	else:
		flash("Please login to view Portfolio")
		return render_template("login.html", title = "Login", heading = "Login", type = "portfolio")
def stockResearch():
	if "logged_in" in session:
		data = db.get_portfolio(session["logged_in"])
		return render_template("stockResearch.html", portfolio_data = data, title = "Stock Search", heading = "Stock Search", logged_in = True)
	else:
		flash("Please login to view Stock Research")
		return render_template("login.html", title = "Login", heading = "Login", type = "stockResearch")
def watchlist():
	if "logged_in" in session:
		data = db.get_portfolio(session["logged_in"])
		watchlist_data = db.get_watchlist(session["logged_in"])
		for each in watchlist_data:
			each[0] = info.getStocks(each[1].lower())
		return render_template("watchlist.html", portfolio_data = data, watchlist = watchlist_data, title = "Watchlist", heading = "Watchlist", logged_in = True)
	else:
		flash ("Please login to view Watchlist")
		return render_template("login.html", title = "Login", heading = "Login", type = "watchlist")#redirect(url_for("login"))
def stockResults():
	data = db.get_portfolio(session["logged_in"])
	if "logged_in" in session:

		retval = {}
		#If the user hasn't inputted anything
		if (request.args["stock_info"] == ""):
			flash ("Please enter a company name")
			return (redirect(url_for("stockResearch")))

		#If the user comes form the watchlist.
		if (request.args["stock_info"].find("{*}") != -1):
			companyCode = request.args["stock_info"].replace("{*}watchlist", "")

			company_info = info.getStocks(companyCode)
			company_info["ytdChange"] = round(company_info["ytdChange"], 5)
			watchlistYet = db.check_watchlist(session["logged_in"], companyCode)
					        #[companyNAme + search_that_led, TRUE/FALSE]
			watchlist_info = [companyCode + "{!{!!}!}" + request.args["stock_info"], watchlistYet]
			#{Actual company name: [companyInfo, [companyName + search, T/F]]}
			retval[company_info["companyName"]] = [company_info, watchlist_info]

		else:
			#print(request.args["stock_info"])
			search = " " + request.args["stock_info"].lower().replace("|~|~|", " ").replace("&", "and").replace(".", " ") + " "
			companyCode = info.getSymbol(search)
			if (companyCode == "NONE"):
				print("bad search...")
				flash ("No company of that name found in our database...")
				return redirect(url_for("stockResearch"))

			#Each will hold a list with all the company info.
			for each in companyCode:
				#print(each)
				company_info = info.getStocks(each)
				company_info["ytdChange"] = round(company_info["ytdChange"], 5)
				#print(company_info)

				companyName = companyCode[each].replace(" ", "|~|~|")
				watchlistYet = db.check_watchlist(session["logged_in"], each.lower())
					            #[companyCode + search_that_led, TRUE/FALSE]
				watchlist_info = [each.lower() + "{!{!!}!}" + request.args["stock_info"].replace(" ", "|~|~|"), watchlistYet]

				retval[companyCode[each]] = [company_info, watchlist_info]

		return render_template("stockResults.html", portfolio_data = data, title = "Stock Results", heading = "Stock Results", logged_in = True, companyInfo = retval)
	else:
		return render_template("login.html", title = "Login", heading = "Login", type = "stockResearch")
def articles():
	#print(request.form)
	query = request.args["article_search"]
	if query.strip() == "":
		query = "stock"
	dict= info.getArticles(query)
	if dict == None:
		flash("Invalid API KEY")
		return render_template("login.html", title = "Login", heading = "Login", type = "watchlist")#redirect(url_for("login"))
	if len(dict) < 1:
		flash("No articles found. Try again")
	if "logged_in" in session:
		data = db.get_portfolio(session["logged_in"])
		return render_template("news.html", portfolio_data = data, title = "Article Results", heading = "Article Results", articles = dict, logged_in= True)
	else:
		return render_template("news.html", title = "Article Results", heading = "Article Results", articles = dict, logged_in= False)
def sellStock():
	print(request.args)
	data = []
	for each in request.args:
		if request.args[each] == "Sell Stocks":
			data = each.replace(" ", "").split("|~~|")
			print(data)
			print("^data")
			break
	code = data[0]
	paid = data[1]
	sell = round(float(data[2]) , 2)
	numS = data[3]

	currPortfolio = db.get_portfolio(session["logged_in"])
	new_buying_power = currPortfolio[3] + sell
	new_cash = currPortfolio[3] + sell
	new_account_val = new_buying_power
	new_annual_ret = round((new_account_val / 100000.0) - 1.00, 2)
	db.add_profile(session["logged_in"],round(new_account_val), round(new_buying_power), round(new_cash), new_annual_ret)

	db.remove_stock(session["logged_in"], code, paid, numS)
	return redirect(url_for("portfolio"))
def buyStock():
	print(request.args)
	for each in request.args:
		if request.args[each] == "Buy Stock":
			data = each.replace(" ", "").split("|~~|")
			break
	search = data[2].split("{!{!!}!}")[1]
	companyCode = data[0].lower()
	stockPrice = round(float(data[1]), 2)
	print(data)
	print(search)
	if (request.args["stock_buy"] == "" ):
		flash("Invalid number of stocks.")
		return redirect(url_for("stockResults" , stock_info = search))
	numStocks = int(request.args["stock_buy"])
	if ( numStocks <= 0):
		flash("Invalid number of stocks.")
		return redirect(url_for("stockResults" , stock_info = search))
	totalPrice = round(stockPrice * numStocks, 2)
	currPortfolio = db.get_portfolio(session["logged_in"])

	if ( totalPrice > currPortfolio[2] ):
		flash("You don't have enough money to buy this.")
		return redirect(url_for("stockResults" , stock_info = search))

	db.buy_stock(session["logged_in"], companyCode, numStocks, totalPrice)

	new_buying_power = currPortfolio[3] - totalPrice
	new_account_val = new_buying_power + info.getStocks(companyCode)["latestPrice"]
	new_cash = currPortfolio[3] - totalPrice
	new_annual_ret = round((new_account_val / 100000.0) - 1.00, 2)
	print (new_annual_ret)

	db.add_profile(session["logged_in"],round(new_account_val, 2), round(new_buying_power, 2), round(new_cash, 2), new_annual_ret)

	return redirect(url_for("portfolio"))
def home():
	if "logged_in" in session:
		data = db.get_portfolio(session["logged_in"])
		return render_template("home.html", title = "Home", heading = "Hello " + session["logged_in"] + "!", user = session["logged_in"], logged_in = True, portfolio_data = data)
	return render_template("home.html", title = "Home", heading = "Hello Guest!", logged_in = False)