import sys, os, json
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from models import Session, User, DailyNutrition
from download import login, save_file
session = Session()

PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
NUTRITION_DIR = os.path.join(PROJECT_DIR, 'nutrition_json')


URL = "http://www.mapmyfitness.com/nutrition/ajax/daily_calorie_budget"
def main():
	create_save_dir()
	for user in session.query(User).all():
		browser = webdriver.Firefox()
		browser.get("https://mapmyfitness.com/auth/login")
		login(browser, user)
		download_json(browser, user)
		browser.quit()
	print "Finished downloading json files"
	for user in session.query(User).all():
		with open(os.path.join(NUTRITION_DIR, "{}.json".format(user.id))) as f:
			data = json.load(f)
		user_info = DailyNutrition(user_id=user.id)
		user_info.set_time()
		user_info.set_fields(data)
		session.add(user_info)
	session.commit()
		
def create_save_dir():
	if not os.path.isdir(NUTRITION_DIR):
		print "Making {}".format(NUTRITION_DIR)
		os.mkdir(NUTRITION_DIR)

def download_json(browser,user):
	filename = os.path.join(NUTRITION_DIR, "{}.json".format(user.id))
	if not os.path.exists(filename):
		html = get_json(browser)
		save_file(html, filename)

	else:
		print "Already downloaded {}".format(filename)

def get_json(browser):
	browser.get(URL)
	html = browser.find_element_by_tag_name('pre').text
	return html

if __name__ == "__main__":
	main()
