"""Puts an mta static data csv file into mongodb"""

import csv

def csv_dicts(fname):
    """runs a csv file through match_kv"""
    with open(fname) as fcsv:
        rows = list(csv.reader(fcsv))
    return match_kv(rows[0], rows[1:])

def match_kv(keys, values):
    """Matches keys and values"""
    result = []
    for vals in values:
        obj = {}
        location = {}
        for i, k in enumerate(keys):
            # using geo_json for stops
            if k == 'stop_lon':
                location['lon'] = float(vals[i])
            elif k == 'stop_lat':
                location['lat'] = float(vals[i])
            else:
                obj[k] = vals[i]
        if len(location) > 0:
            obj['location'] = {'type':'Point',
                               'coordinates':(location['lon'], location['lat'])}
            location = {}
        result.append(obj)
    return result

from pymongo import MongoClient, GEOSPHERE

def update_database(filename, collection, uniquekey):
    """actually updates the database"""
    vals = csv_dicts(filename)
    subtime = MongoClient().subwaytime
    hasloc = False
    for val in vals:
        subtime[collection].update({uniquekey:val[uniquekey]}, val, upsert=True)
        hasloc = hasloc or 'location' in val
    if hasloc:
        subtime[collection].ensure_index([('location', GEOSPHERE)])
        print 'indexing by location'
    print 'inserted %d records in subwaytime.%s'%(len(vals), collection)

def cli():
    """CLI for this thingermerbob"""
    import sys
    if len(sys.argv) < 2:
        filename = raw_input('update database with file: ')
    else:
        filename = sys.argv[1]
    collection = filename.split('.')[0]
    collection = raw_input('name collection [defaults to %s]: '%collection)
    ukey = raw_input('unique field: ')
    update_database(filename, collection, ukey)

if __name__ == '__main__':
    cli()
