
# python standard library
import os
import json
from datetime import date
from datetime import timedelta
from urllib.parse import urljoin
import xml
from pprint import pprint
from collections import defaultdict

# third party
import requests
import xmltodict

class URLConstants(object):
    __slots__ = ()
    address = "http://web.mta.info"
    path =  urljoin(address, "/developers/data/bandt/tbta_plaza/")
    file_base = urljoin(path, "PLAZA_DAILY_TRAFFIC_{date}.xml")
    date_format = "%Y%m%d"

today = date.today()
last_monday = today - timedelta(today.weekday())
last_monday_string = last_monday.strftime(URLConstants.date_format)

file_url = URLConstants.file_base.format(date=last_monday_string)
print(file_url)

print("So we're pulling data from {0}.".format(last_monday.strftime("%B %d, %Y")))

response = requests.get(file_url)

try:
    data = xmltodict.parse(response.text)
except xml.parsers.expat.ExpatError as error:
    print(error)

data = xmltodict.parse(response.text.lstrip('\n'))
data = json.loads(json.dumps(data))

class DataConstants(object):
    __slots__ = ()
    root = "message"
    summaries = "TransSummary"
    date = "@Date"
    facility = 'facility'
    paid_cash = "@cash-count"
    ezpay = '@etc-count'
    identifier = '@id'

facilities = {'1': "Robert F. Kennedy Bridge Bronx Plaza",
              '2': "Robert F. Kennedy Bridge Manhattan Plaza",
              '3': "Bronx-Whitestone Bridge",
              '4': "Henry Hudson Bridge",
              '5': "Marine Parkway-Gil Hodges Memorial Bridge",
              '6': "Cross Bay Veterans Memorial Bridge",
              '7': "Queens Midtown Tunnel",
              '8': "Brooklyn-Battery Tunnel",
              '9': "Throgs Neck Bridge",
              '11': "Verrazano-Narrows Bridge"}

summaries = data[DataConstants.root][DataConstants.summaries]
pprint(summaries[0])

data_dict = defaultdict(lambda: 0)
for summary in summaries:
    for facility in summary[DataConstants.facility]:
        data_dict[facility[DataConstants.identifier]] += int(facility[DataConstants.paid_cash])
        data_dict[facility[DataConstants.identifier]] += int(facility[DataConstants.ezpay])
for facility, count in data_dict.items():
    data_dict[facility] = count/7.

for facility, mean in data_dict.items():
    print("   {0},{1:.2f}".format(facilities[facility], mean))

output = {'total':[ {'id': identifier,
                     "name": facilities[identifier],
                   'count': data_dict[identifier]} for identifier in sorted(data_dict.keys())]}
with open("mean_counts.json", 'w') as countwriter:
    json.dump(output, countwriter)

print(INCLUDE_D3)
print(INCLUDE_JAVASCRIPT.format('mean_bt_counts.js'))
print('   <script>')
print('   d3.json("{0}", mean_bt_counts);'.format(DOWNLOADS_PATH.format("mean_counts.json")))
print('   </script>')