#!/usr/bin/env python

import sys
import os.path
import logging
import geojson
import io

import mapzen.whosonfirst.utils
import mapzen.whosonfirst.export
import mapzen.whosonfirst.validator

if __name__ == '__main__':

    import optparse
    opt_parser = optparse.OptionParser()

    opt_parser.add_option('-e', '--exporter', dest='exporter', action='store', default='flatfile', help='')

    opt_parser.add_option('-s', '--source', dest='source', action='store', default=None, help='')

    opt_parser.add_option('-i', '--id', dest='id', action='store', default=None, help='')
    opt_parser.add_option('-p', '--path', dest='path', action='store', default=None, help='')

    opt_parser.add_option('-c', '--collection', dest='feature_collection', action='store_true', default=False, help='')

    opt_parser.add_option('-a', '--alt', dest='alt', action='store', default=None, help='')
    opt_parser.add_option('-d', '--display', dest='display', action='store', default=None, help='')

    opt_parser.add_option('--stdin', dest='stdin', action='store_true', default=False, help='')
    opt_parser.add_option('--debug', dest='debug', action='store_true', default=False, help='')

    opt_parser.add_option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Be chatty (default is false)')

    options, args = opt_parser.parse_args()

    if options.verbose:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.INFO)

    exporter = None

    if options.exporter == "flatfile":
        source = os.path.abspath(options.source)
        exporter = mapzen.whosonfirst.export.flatfile(source, debug=options.debug)
    elif options.exporter == "stdout":
        exporter = mapzen.whosonfirst.export.stdout(debug=options.debug)
    else:
        logging.error("Invalid exporter")
        sys.exit(1)

    if options.id:
        id = int(options.id)
        feature = mapzen.whosonfirst.utils.load([source], id, alt=options.alt, display=options.display)
    elif options.path:

        fh = open(options.path, 'r')
        feature = geojson.load(fh)

    elif options.stdin:
        feature = geojson.load(sys.stdin)

    else:
        logging.error("Missing feature or feature ID")
        sys.exit()

    #

    def features():

        if options.feature_collection:

            for f in feature['features']:
                yield f

        else:

            yield feature

    #

    for f in features():

        vld = mapzen.whosonfirst.validator.validator()
        rpt = vld.validate_feature(f)

        if not rpt.ok():
            logging.error("validation failed for feature")

            if options.verbose:

                fh = io.StringIO()
                rpt.print_report(fh)
                fh.seek(0)

                logging.debug(fh.readlines())

            sys.exit()

        exporter.export_feature(f, alt=options.alt, display=options.display)

    sys.exit()
