import sys, os, time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import ConfigParser
import calendar

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

config = ConfigParser.ConfigParser()
cal = calendar.Calendar()
try:
	config.read('config.ini')
	EMAIL = config.get('user', 'email')
	PASSWD = config.get('user', 'password')
except ConfigParser.NoSectionError:
	sys.exit("Improperly configured config.ini file")

URL = "http://www.mapmyfitness.com/nutrition/ajax/daily_calorie_budget?date="
def main():
	create_save_dir()
	browser = webdriver.Firefox()
	browser.get("https://www.mapmyfitness.com/auth/login/")
	login(browser)
	for month in range(1, 6):
		download_json(browser, month)

def login(browser, user):
	email = browser.find_element_by_name('email')
	password = browser.find_element_by_name("password")
	submit = browser.find_element_by_id("login_button")

	email.send_keys(user.name)
	password.send_keys(user.password)
	submit.send_keys(Keys.RETURN)
	time.sleep(5)

def download_json(browser, month):
	for day in cal.itermonthdays(2015, month):
		if day != 0:
			dateParam = "2015-{}-{}".format(month, day)
			filename = os.path.join(NUTRITION_DIR, "{}.json".format(dateParam))
			dateParam = "2015-{}-{}".format(month, day)
		else:
			continue

		if not os.path.exists(filename):
			html = get_json(browser, dateParam)
			save_file(html, filename)

def save_file(html, filename):
	try:
		with open(filename, 'w') as f:
			f.write(html)
	except IOError:
			print "Could not write to file {}".format(filename)
		
def get_json(browser, dateParam):
	url = URL + dateParam
	print url
	browser.get(url)
	html = browser.find_element_by_tag_name('pre').text
	return html

def create_save_dir():
	if not os.path.isdir(NUTRITION_DIR):
		print "Making {}".format(NUTRITION_DIR)
		os.mkdir(NUTRITION_DIR)

if __name__ == "__main__":
	main()
