#!/user/bin/python
import bottle
import bottle_mysql
import re
import requests
import urllib2
import webbrowser
from array import *
from pprint import pprint
from bottle import static_file, route, run, request,response, template, static_file
from urllib2 import urlopen 

app = bottle.Bottle()
plugin = bottle_mysql.Plugin(dbuser='user', dbpass="", dbname='nordicFantasy')
app.install(plugin)

@route('/<filename>.css')
def stylesheets(filename):
	print("help me")
	return static_file('{}.css'.format(filename), root='static')

@route('/static/<filename>')
def server_static(filename):
	print("something might be working")
	return static_file(filename, root='/static/')

@app.route('/loginn')
def show(db):
	pprint("login")
	return bottle.template("loginPage")

@route('/static/:path#.+#', name='static')
def static(path):
	return static_file(path, root='static')

@app.route('/editUser')
def show(db):
	userName = request.get_cookie("userName", secret="batman")
	data = userName
	return bottle.template("editUser", data = data)

@app.route('/edit', method="POST")
def show(db):
	userName = request.get_cookie("userName", secret="batman")
	newName = request.forms.get('newName')
	oldPass1 = request.forms.get('oldPass1')
	oldPass2 = request.forms.get('oldPass2')
	newPass = request.forms.get('newPass')

	cookie = getCookie()
# getting the password
	getPass = ("select password from myUser where userName = '%s';" %userName)
	print(getPass , userName)
	db.execute(getPass)
	results = db.fetchall()
	userN = " "

	passW = str(results[0]["password"])	
	print("oldPass ",passW)

	if oldPass1 == passW:
		if oldPass2 == passW:
			mysql = ("update myUser set password = '%s' where" % newPass) 
			mysql += (" userName = '%s';" % userName)
			print(mysql)
			db.execute(mysql)
# getting the newUserName
	print("getting newUserName")
	getName = ("select * from myUser where userName = '%s';" %newName)
	db.execute(getName)
	name = db.fetchall()
	print("this is name ", name)
	if newName:
		if name:
			print("the username is taken")
		else:
			print("the username is not taken")
			mysql = ("update myUser set userName = '%s' " % newName)
			mysql += ("where userName = '%s';" % userName)
			print(mysql)
			db.execute(mysql)
			userName = newName
			response.set_cookie("userName", userName, secret='batman')

	return bottle.template("editUser", data = userName)
@app.route('/loginPage', method= "POST")
def show(db):
	pprint("checkUser")
	userName = request.forms.get('userName')
	password = request.forms.get('password')
	pprint(userName)
	pprint(password)	
	check = ("select userName, league1, team1 from myUser where password = %s and userName = %s;")
	data = (password, userName)
	db.execute(check, data)
	results = db.fetchall()
	if results:
		color = "blue"
		info = color
#		for row in results:
		info = str(results[0]["userName"])
		response.set_cookie("userName", info, secret='batman')
		info = str(results[0]["league1"])
		response.set_cookie("userLeague", info, secret='batman')
		info = str(results[0]["team1"])
		print(info)
		response.set_cookie("userTeam", info, secret='batman')
		db.execute("select * from myTeam where teamID = '%s';" % info)
		data = db.fetchall()
		return bottle.template("homePage", data = data)
	else:
		color = "red"
		pprint("should go to loginPage")
	pprint("yes it did work")
	return bottle.template("loginPage", color = color)


@app.route('/newUser', method="POST")
def show(db):
	pprint("newUser")
	return bottle.template("newUser")	

@app.route('/checkNewUser', method="POST")
def show(db):
	pprint("checkNewUser")
	userName2 = request.forms.get('userName')
	password2 = request.forms.get('password')
	pprint(userName2)
	mysqlCode = ("select userName from myUser where userName = '%s';" % userName2)
	pprint(mysqlCode)
	db.execute(mysqlCode)
	results = db.fetchall()
	if results:
		color = "red"
		return bottle.template("newUser")
	else:
		pattern = "^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,16}"
		passwordValidated = re.match(pattern, password2)
		color = "red"
		if passwordValidated:
			color = "green"
			check =("insert into myUser(userName, password) values(%s, %s);")
			data = (userName2, password2)
			pprint(color)
			db.execute(check, data)
			response.set_cookie("userName", userName2, secret='batman')
			response.set_cookie("userLeague", "", secret='batman')
			response.set_cookie("userTeam", "", secret='batman')

		else:
			color = "didn't pass password validation"

	return bottle.template("homePage")
	
@app.route('/checkNewLeague', method ="POST")
def show(db):
	pprint("checkNewLeague")
	name = request.forms.get('name')
	password = request.forms.get('password')
	type = request.forms.get('type')
	pprint(name)
	pprint(password)
	pprint(type)
	mysqlCode = ("select leagueName from myLeague where leagueName = '%s';" % name)
	db.execute(mysqlCode)
	results = db.fetchall()
	if results:
		color = "red"
		return bottle.template("createLeague")
	else:
		check = ("insert into myLeague(leagueName,password,type) values(%s,%s,%s);")
		data =(name, password, type)
		db.execute(check, data)
	return bottle.template("homePage")

@app.route('/homePage', method = "POST")
def show(db):
	pprint("homePage")
	cookie = getCookie()
	userName = cookie[0]
	userLeague = cookie[1]
	userTeam= cookie[2]
	print("this is userName: ",userName)
	print("this is userLeague: ",userLeague)
	print("this is userTeam: ",userTeam)
	return bottle.template("homePage")
@app.route('/homePage2')
def show(db):
	pprint("homePage")
	cookie = getCookie()
	mysqlCode = ("select team1, teamW1, teamL1, points1, league1, team2, teamW2, teamL2, points2, league2 from myUser where userName = '%s';" % cookie[0])
	pprint(mysqlCode)
	db.execute(mysqlCode)
	data = db.fetchall()
	leagueID1 = str(data[0]["league1"])
	mySql = ("select userName, teamW1, teamL1 from myUser where userID in (select userID from myTeam where leagueID = '%s');" % leagueID1)
	db.execute(mySql)
	userIDs = db.fetchall()
		
#getting my first team
	code = str(data[0]["league1"])
	print(code)
	sqlCode = ("select leagueName from myLeague where leagueID = '%s';" % code)
	pprint(sqlCode)
	db.execute(sqlCode)
	data = db.fetchall()
	print(data)
	return bottle.template("homePage", data = data, league = userIDs)

@app.route('/updateWorldCupPoints')
def show(db):
#update the worldcup athelete page
	nation = nations()	
	point = points()
	name = names()
	namesID = nameID()
	size = len(name)
	i = 0
	while i < size:
		mySqlCode = ("insert into mySkiers(id,athlete,country,points) values (%s,%s,%s,%s);")
		data2 = (namesID[i],name[i],nation[i],point[i])
		db.execute(mySqlCode, data2)
		i = i +1
	return bottle.template("updateWorldCupPoints")

@app.route('/leaguePage')
def show(db):
	pprint("leaguePage")
	db.execute("select leagueName from myLeague;")
	data = db.fetchall()
	userName = request.get_cookie("userName", secret="batman")
	userLeague = request.get_cookie("userLeague", secret="batman")
	userTeam= request.get_cookie("userTeam", secret="batman")
	print("this is userName: ",userName)
	print("this is userLeague: ",userLeague)
	print("this is userTeam: ",userTeam)
	return bottle.template("leaguePage", data = data)

@app.route('/createLeague')
def show(db):
	pprint("createLeague")
	webbrowser.open('http://euclid.nmu.edu/~selfstro/seniorProject/createLeague.html')
	return bottle.template("createLeague")

@app.route('/skierPage')
def show(db):
	pprint("skierPage")
	db.execute("select * from mySkiers;")
	data = db.fetchall()
	db.execute("select distinct country from mySkiers order by country;")
	nation = db.fetchall()
	return bottle.template("skierPage", data = data, nation = nation)

@app.route('/filterSkiers', method="POST")
def show(db):
#	country = request.forms.get('country')
	country = request.POST.getlist('country')
	print(country)
	size = len(country)
	print(size)
	tmp = country[0]
	sql = ("select * from mySkiers where country = '%s'" %tmp)
	i = 1
	while i < size:
		print(country[i])
		tmp = country[i]
		sql += (" or country = '%s'" %tmp)
		i = i + 1
#		db.execute(check, data)
	sql += ";"
	print(sql)
#	db.execute("select * from mySkiers where country = '%s';" % country[0])
	db.execute(sql)
	data = db.fetchall()
	db.execute("select distinct country from mySkiers order by country;")
	nation = db.fetchall()
	return bottle.template("skierPage", data = data, nation = nation)

def altElement(a):
	newList = a[::2]
	return newList
	
def createList(a):
	i = 0
	newlist=[]
	temp = ""
	size = len(a)
	size = size
	while i < size:
		print(a[i][0])
		temp = a[i][0]
		newlist.insert(i,temp)
		i= i+1
	return newlist

def create2List(a,b):
	i = 0
	newlist=[]
	temp = ""
	size = len(a)
	size = size
	while i < size:
		print(a[i][0])
		temp = a[i][0]
		temp2 = b[i][0]
		newlist.insert(i,temp,temp2)
		i= i+1
	return newlist

def alt(a):
	newList = a[::16]
	return newList
def getNews():
	url = "http://www.fis-ski.com/cross-country//news-multimedia/news/"
	response = urlopen(url)
	data = str(response.read())
	pattern = '(article=[a-z]+(-[a-z]+)*.html">[A-Za-z]+( ([a-zA-Z]|!|:|-)*)*)'
	firstFind = re.findall(pattern, data)
	firstString = ' '.join(wcp)
	


def getURL():
	url = "http://www.fis-ski.com/cross-country/leader-board/"
	response = urlopen(url)
	data = str(response.read())	
	return data

def nations():
#nations
	data = getURL()
	patternNation = '(title="[A-Z][a-z]+)'
	reFactorNation = '([A-Z][a-z]+)'
	wcp = re.findall(patternNation, data)	
	newthing = ' '.join(wcp)
	nations = re.findall(reFactorNation, newthing)
	nations.pop(0)
	nations.pop(0)
	nations.pop(0)
	nations.pop(0)
	return nations

def points():
#world cup points
	patternWCP = '(class="dcm-tcr">[0-9]{0,4})'
	reFactorWCP = '([0-9]{1,4})'
	data = getURL()
	points = re.findall(patternWCP , data)
	tmp = ' '.join(points)
	cupPoints = re.findall(reFactorWCP, tmp)
	return cupPoints

def names():
#name
	data = getURL()
	pattern = '([A-Z]+(  [A-Za-z|-]+)+)'
	names = re.findall(pattern, data)
	justNames = createList(names)
	jNames = altElement(justNames)
	return jNames

def nameID():
#names+ID
	data = getURL()
	pattern2 = '([a-z]+(-[a-z|-]+)+-[0-9]{4,6})'
	id = re.findall(pattern2,data)
	ids = createList(id)
	ids.pop(0)
	ids.pop(0)
	ids.pop(0)
	ids.pop(0)
	ids.pop(0)
	ids.pop(0)
	ids.pop(-1)
	return ids

def getCookie():
	userName = request.get_cookie("userName", secret="batman")
	userLeague = request.get_cookie("userLeague", secret="batman")
	userTeam= request.get_cookie("userTeam", secret="batman")
	print("this is userName: ",userName)
	print("this is userLeague: ",userLeague)
	print("this is userTeam: ",userTeam)
	cookie = [ userName, userLeague, userTeam]
	print(cookie[0])
	print(cookie[1])
	print(cookie[2])
	return cookie


app.run(host='euclid.nmu.edu',port= 5678)

