import sys
sys.stdout = sys.stderr

import os
import atexit
import threading
import cherrypy
import MySQLdb
import pickle
import subprocess
from collections import OrderedDict
from datetime import datetime
from dateutil import parser

db = MySQLdb.connect(
  host="127.0.0.1",
  user="divvy",
  passwd="keepC4LM",
  db="divvy"
)

if subprocess.check_output("hostname") == "praxis\n":
  PATH = ""
else:
  PATH = "/var/www/cs424/p2/py"

c = db.cursor()

def parse_age(age):
  """Parse age groups... when you get an age, return the range as its displayed
  in the pie chart.  This is currently unused.

  Args:
    age - int

  Returns:
    tuple - two ints, uninclusive
  """
  if age == "Under 20":
    return (0, 20)
  elif age == "20-29":
    return (19,30)
  elif age == "30-39":
    return (29, 40)
  elif age == "40-49":
    return (39, 50)
  elif age == "50-59":
    return (49, 60)
  elif age == "60+":
    return (59, 180)

def parse_time_of_day(time_of_day):
  """given a time of day string, return the time range (inclusive).

  Args:
    time_of_day - string, one of morning, lunch, "after work", or evening

  Returns:
    a two tuple of inclusive time range (low, high)
  """
  if time_of_day == "morning":
    return(6, 9)
  elif time_of_day == "lunch":
    return(11,13)
  elif time_of_day == "after work":
    return(4, 7)
  elif time_of_day == "evening":
    return(7,9)
 
def store_popularity_groups():
  """Stores popularity in a pickle.  To be run offline."""
  with open("stations.pickle", "rb") as f:
    stations = pickle.load(f)
  with open("id_popularity.pickle", "rb") as f:
    id_pop = pickle.load(f)

  pop_rankings = id_pop.values()
  pop_rankings.sort()
  d = {
    0: [], 1: [], 2: [], 3: [], 4:[], 5:[], 6:[]
  }
  for sid, count in id_pop.items():
    if count in pop_rankings[0:10]:
      d[0].append(stations[sid])
    elif count in pop_rankings[10:50]:
      d[1].append(stations[sid])
    elif count in pop_rankings[50:100]:
      d[2].append(stations[sid])
    elif count in pop_rankings[100:150]:
      d[3].append(stations[sid])
    elif count in pop_rankings[150:200]:
      d[4].append(stations[sid])
    elif count in pop_rankings[200:250]:
      d[5].append(stations[sid])
    elif count in pop_rankings[250:300]:
      d[6].append(stations[sid])

  with open("popularity.pickle", "wb") as f: