import time

from bs4 import BeautifulSoup
import requests
import dataset

def has_specified_class(tag, classname):
    return tag.get('class') == [classname]

def grab_times (bus_strings, stop_code):
    url = "http://www.mybustracker.co.uk/"
    params = dict()
    params['module'] = "consult"
    params['mode'] = "busStopQuickSearch"
    params['busStopCode'] = str(stop_code)
    request = requests.get(url=url, params=params) 
    data = request.text
    soup = BeautifulSoup(data)
    rows = [ x for x in soup.find_all('tr') ]
    results = []
    for row in rows:
        services = [ td.string for td in row('td') if has_specified_class(td, "service") ]
        timecells = [ td for td in row('td') if has_specified_class(td, "time") ]
        if len(services) < 1 or len(timecells) < 1:
            continue
        service = services[0]
        timecell = timecells[0]
        time_spans = timecell("span")
        time_span = time_spans[0]
        if service and service in bus_strings:
            pair = (service, time_span.string)
            results.append(pair)
    return results

def grab_next_bus(bus, stop_code):
    bus_string = str(bus)
    results = grab_times([ bus_string ], stop_code)
    time_strings = [ time for (service, time) in results ]
    if time_strings == []:
        return 60
    if "DUE" in time_strings:
        return 0
    def parse_time(t):
        if ":" in t:
            return 60
        else:
            return int(t)
    times = [ parse_time(t) for t in time_strings ]
    return min(times + [60])

def report_times(time_string, bus_times):
    columns = [ time_string ] + [ x + ", " + y for (x,y) in bus_times ]
    line = ", ".join(columns)
    print(line)

def run(output_filename):
    # Storing the header names and stop codes together like this means that we
    # are less likely to make a mistake below and get them out of order
    stops = [ ("North Bridge", 36234754),
              ("Cameron Toll", 36234845), 
              ("Lasswade Road", 36237956),
              ("Park Road", 64323292)
            ]
    names = [ n for (n, s) in stops ]
    stop_codes = [ s for (n, s) in stops ]
    db = dataset.connect('sqlite:///mydatabase.db')
    table = db['due-times']
    while(True):
        time_struct = time.localtime()
        for stop_code in stop_codes:
            next_bus_time = grab_next_bus(31, stop_code)
            table.insert(dict(time=time_struct,
                              bus=31, 
                              stop_code=stop_code,
                              next_bus=next_bus_time))
        # Could instead work out how long that took and then sleep for
        # 30 - how long it took.
        time.sleep(30)

if __name__ == "__main__":
    import sys
    run (sys.argv[1])
