#! /usr/bin/env python
'''Libraries for the SUMO traffic simulation software
http://sumo.dlr.de
'''

import csv

def loadTazEdges(inFilename):
    '''Converts list of OSM edges per OSM edge and groups per TAZ'''
    data = []
    tazs = {}
    with open(inFilename,'r') as f:
	csv_reader = csv.reader(f, delimiter=",")
	next(csv_reader, None)  # skip the headers
	for row in csv_reader:
	    data.append(row)

    for datum in data:
	if len(datum) > 5 and datum[5] is not None:
	    tazID = datum[3]
	    for edge in datum[15:]:
                if len(edge) > 0:
		    if edge is not None:
                        if tazID in tazs:
                            if edge not in tazs[tazID]:
                                tazs[tazID].append(edge)
                        else:
                            tazs[tazID] = [edge]
    return tazs
        
def saveTazEdges(outFilename, tazs):
    with open(outFilename,'w') as out:
	out.write('<tazs>\n')				
	for tazID in tazs:
	    out.write('<taz id="{}" edges="'.format(tazID)+' '.join(tazs[tazID])+'"/>\n')
	out.write('</tazs>\n')
    
# TODO add utils from process-cyber.py?
        
# if __name__ == "__main__":
#     import doctest
#     import unittest
#     suite = doctest.DocFileSuite('tests/sumo.txt')
#     #suite = doctest.DocTestSuite()
#     unittest.TextTestRunner().run(suite)
