#!/usr/bin/env python

import sys
import os.path
import logging
import geojson
import datetime

import mapzen.whosonfirst.search
import mapzen.whosonfirst.utils

if __name__ == '__main__':

    import optparse
    opt_parser = optparse.OptionParser()

    opt_parser.add_option('--host', dest='host', action='store', default='localhost', help='What host your search index lives (default is localhost)')
    opt_parser.add_option('--port', dest='port', action='store', default=9200, help='What port your search index lives on (default is 9200)')
    opt_parser.add_option('--timeout', dest='timeout', action='store', default=600, help='Timeout in seconds for talking to you search index lives on (default is 600)')
    opt_parser.add_option('--tidy', dest='tidy', action='store_true', default=False, help='Remove files after they are processed (default is False)')

    opt_parser.add_option('--slack', dest='slack', action='store_true', default=False, help='Report statistics to a Slack channel (default is False)')
    opt_parser.add_option('--slack-config', dest='slack_config', action='store', default=None, help='The path to your Slack config file')

    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.WARNING)

    idx = mapzen.whosonfirst.search.index(host=options.host, port=options.port, timeout=options.timeout)

    dt1 = datetime.datetime.now()

    for path in args:
        path = os.path.abspath(path)
        idx.index_filelist(path)

        if options.tidy:
            os.unlink(path)

    dt2 = datetime.datetime.now()
    diff = dt2 - dt1

    msg = "time to index filelist (%s) : %s" % (len(args), diff)
    logging.info(msg)

    # this could probably be moved in to a wrapper function
    # ... but it hasn't been yet (20151209/thisisaaronland)

    if options.slack:

        try:
            import json
            import slack.api.client			# https://github.com/cooperhewitt/py-slack-api
            
            fh = open(options.slack_config, 'r')	# this assumes a slackcat style config file
            cfg = json.load(fh)

            whoami = sys.argv[0]
            whoami = os.path.basename(whoami)

            wh = slack.api.client.Webhook(cfg.get('webhook_url'))
            wh.send("[%s] %s" % (whoami, msg))

        except Exception, e:
            logging.error("Failed to send msg to Slack, because %s" % e)

    sys.exit()

