import forexDataScrape as fds 
import dbapi
import datetime
import itertools


def getData(ticker):

	endTime = fds.startOfDay(datetime.datetime.utcnow())
	#endTime = endTime.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
	startTime = fds.startOfDay(endTime - datetime.timedelta(days=1))
	interval = "1m"

	fds.execScrape(ticker, startTime, endTime, interval)
	data = fds.execScrape(ticker, startTime, endTime, "1d")

	return data


#data = {ticker : data, ticker2: data2}
def updateTicker(ticker, data, old):
 	cols = db.formats["forex"]["cols"]

 	print old
	update = {}
 	for i in range(0,len(cols)):
 		col = cols[i]
 		if col == "current_rate":
 			update[col] = data["quote"]["close"][0]
		elif col == "last_rate":
			if old[ticker][i-1] == None:
				update[col] = 0.
			else:
				update[col] = old[ticker][i-1]
		elif col == "change_day":
			if update["last_rate"] == 0:
				update[col] = 0.
			else:
				update[col] = (data["quote"]["close"][0]/update["last_rate"] - 1)*100
		else:
			update[col] = old[ticker][i]
	
	print update

	db.insert("forex", update)


def updateForex():
	currencies = ["USD", "EUR", "JPY", "GBP", "CHF", "CAD", "AUD", "NZD"]

 	currencyPairs = list(itertools.permutations(currencies, 2))
	currencyTickers = []

	for pair in currencyPairs:
 		currencyTickers.append(pair[0] + pair[1] + "=X")

	db = dbapi.API()
	db.connect()
	old = db.getAllData('forex')
	old = mapify(old)

	for ticker in currencyTickers:
		data = getData(ticker)
		updateTicker(ticker,data,old)


#data must be two dimensions
def mapify(data):
	m = {}
	for row in data:
		m[row[0]] = row
	print m
	return m

#def pullPrevData

if __name__ == '__main__':
 	#getData("USDEUR=X")
 	db = dbapi.API()
 	db.connect()
 	updateForex()
@@ -70,16 +70,32 @@
 ertools%0A
+import schedule%0A
 %0A%0Adef ge
@@ -168,87 +168,8 @@
 ())%0A
-%09#endTime = endTime.replace(hour = 0, minute = 0, second = 0, microsecond = 0)%0A
 %09sta
@@ -449,16 +449,20 @@
 ata, old
+, db
 ):%0A %09col
@@ -499,19 +499,8 @@
 %5D%0A%0A 
-%09print old%0A
 %09upd
@@ -963,23 +963,8 @@
 %5D%0A%09%0A
-%09print update%0A%0A
 %09db.
@@ -1415,16 +1415,19 @@
 data,old
+,db
 )%0A%0A%0A#dat
@@ -1517,17 +1517,8 @@
 row%0A
-%09print m%0A
 %09ret
@@ -1528,26 +1528,8 @@
  m%0A%0A
-#def pullPrevData%0A
 %0Aif 
@@ -1558,74 +1558,107 @@
 :%0A %09
-#getData(%22USDEUR=X%22)%0A %09db = dbapi.API()%0A %09db.connect()%0A %09updateForex(
+schedule.every().day.at(%2200:01%22).do(updateForex)%0A %09while 1:%0A %09%09schedule.run_pending()%0A %09%09#time.sleep(1
 )

set up a daily updater for the forex table. Once running it will update everyday at 12:01 am