#! /usr/bin/env python
# SETUPTOOLS_DO_NOT_WRAP

import sys
import traceback
import kmltrack.fileconverter


def parse_argv(argv):
    options = {}
    args = []
    for item in argv:
        if item.startswith('--'):
            item = item[2:]
            if '=' in item:
                key, value = item.split('=', 1)
                options[key] = value
            else:
                options[item] = True
        else:
            args.append(item)

    return args, options


def print_help():
    print """Usage: kmltrack [OPTIONS] INFILE OUTFILE

Options:
    --verify-rows

    --format=msgpack
    --format=json
    --format=csv
      Format is auto-detected from file extension if not specified.

    --map-lat=EXPR        default: float(lat)
    --map-lon=EXPR        default: float(lat)
    --map-timestamp=EXPR  default: d(timestamp)
    --map-course=EXPR     default: float(course)
    --map-color=EXPR      default: float(color)
      Calculate values for the various columns. EXPR is any python
      expression over the row column values available as variables.

    Color should be either a float in the range [0.0, 1.0] or a hex string 'AABBGGRR'
"""



args, options = parse_argv(sys.argv[1:])

if '--help' in options:
    print_help()
else:
    try:

        options['column_map'] = {}
        for key, value in options.iteritems():
            if key.startswith('map-'):
                key = key.split("-", 1)[1]
                options['column_map'][key] = value

        if 'format' not in options and '.' in args[0]:
            options['format'] = args[0].split('.')[-1]

        converter = getattr(kmltrack.fileconverter, "%s_to_kml" % (options['format'],))

        converter(*args, **options)
    except Exception, e:
        print e
        traceback.print_exc()
        print_help()
