from __future__ import absolute_import
from __future__ import print_function

import os
import sys
from argparse import ArgumentParser

if 'SUMO_HOME' in os.environ:
    sys.path.append(os.path.join(os.environ['SUMO_HOME'], 'tools'))
import sumolib  # noqa


def get_options(args=None):
    parser = ArgumentParser(description="Sample routes to match counts")
    parser.add_argument("-t", "--turn-file", dest="turnFile",
                        help="Input turn-count file")
    parser.add_argument("-o", "--output-file", dest="out",
                        help="Output edgeRelations file")
    parser.add_argument("--turn-attribute", dest="turnAttr", default="probability",
                        help="Write turning 'probability' to the given attribute")

    options = parser.parse_args(args=args)
    if options.turnFile is None or options.out is None:
        parser.print_help()
        sys.exit()
    return options


def main(options):
    with open(options.out, 'w') as outf:
        sumolib.writeXMLHeader(outf, "$Id$", "data", "datamode_file.xsd")  # noqa
        for interval in sumolib.xml.parse(options.turnFile, 'interval'):
            outf.write('    <interval begin="%s" end="%s">\n' % (
                interval.begin, interval.end))
            if interval.fromEdge:
                for fromEdge in interval.fromEdge:
                    for toEdge in fromEdge.toEdge:
                        outf.write(' ' * 8 + '<edgeRelation from="%s" to="%s" %s="%s"/>\n' % (
                            fromEdge.id, toEdge.id, options.turnAttr, toEdge.probability))
            outf.write('    </interval>\n')
        outf.write('</edgeRelations>\n')


if __name__ == "__main__":
    main(get_options())
