#!/usr/bin/env python

#
# names-import
#

DESCRIPTION = """Loads FAR and WRA records from CSV files and uploads to Elasticsearch."""

SUBPARSER_TITLE = """Subcommands"""
SUBPARSER_DESCRIPTION = """Additional help is available for each of the following subcommands.
Example:
    $ namesdb import --help
"""
SUBPARSER_HELP = ''

EPILOG = """

    # Create and destroy indexes
    $ namesdb create -H localhost:9200 -i namesdb-stage
    $ namesdb destroy -H localhost:9200 -i namesdb-stage --confirm
    
    # Check status
    $ namesdb status -H localhost:9200 -i namesdb-stage
    
    # Import records
    $ namesdb import -H localhost:9200 -i namesdb-stage /tmp/namesdb-data/far-manzanar.csv
    
    # Delete records
    $ namesdb delete -H localhost:9200 -i namesdb-stage /tmp/namesdb-data/far-manzanar.csv
    
    # Search for record
    $ namesdb search -H localhost:9200 -i namesdb-stage yano
    $ namesdb search -H localhost:9200 -i namesdb-stage "George Takei"
    $ namesdb search -H localhost:9200 -i namesdb-stage 7-manzanar_zoriki_1922_masayuki

Note: You can set environment variables for HOSTS and INDEX.:

    $ export ES_HOSTS=localhost:9200
    $ export ES_INDEX=namesdb-dev

"""


CREATE_DSCR = "Create the specified Elasticsearch index and upload mappings."
CREATE_HELP = """
More details about create function.
"""


DSTROY_DSCR = "Destroy the specified Elasticsearch index and all its records."
DSTROY_HELP = """
Think twice before you do this, then think again.
"""


STATUS_DSCR = "Check status of specified Elasticsearch index."
STATUS_HELP = """
Useful for checking whether or not specified index exits before destroying it.
"""


IMPORT_DSCR = "Import records from CSV file, upload to Elasticsearch."
IMPORT_HELP = """
In normal usage the filename should consist of dataset plus .csv:

    $ namesdb import -H localhost:9200 -i namesdb-stage /tmp/namesdb-data/far-manzanar.csv

If filename does not contain the dataset name, specify using -d/--dataset:

    $ namesdb import -H localhost:9200 -i namesdb-stage -d far-manzanar /tmp/random-file.csv
"""


DELETE_DSCR = "Delete records in CSV file from Elasticsearch."
DELETE_HELP = """
Use this function to delete all records for a given dataset by pointing the function at the CSV file.  To delete only certain records, make a CSV file containing a single column containing NamesDB pseudo IDs, having the column header "m_pseudoid".
"""


SEARCH_DSCR = "Perform search query, return results in raw JSON."
SEARCH_HELP = """
Whatever text follows the HOST and INDEX args will be pasted directly into the body of an Elasticsearch "match" query.

Examples:

    $ namesdb search -H localhost:9200 -i namesdb-stage yano
    $ namesdb search -H localhost:9200 -i namesdb-stage "George Takei"
    $ namesdb search -H localhost:9200 -i namesdb-stage 7-manzanar_zoriki_1922_masayuki

"""
    
import argparse
import os

from namesdb import publish


def main():
    
    # look for HOSTS and INDEX in environment
    if 'ES_HOSTS' in os.environ:
        hostsarg = { 'default': os.environ['ES_HOSTS'] }
    else:
        hostsarg = { 'required': True }
    if 'ES_INDEX' in os.environ:
        indexarg = { 'default': os.environ['ES_INDEX'] }
    else:
        indexarg = { 'required': True }
    
    formatter = argparse.RawDescriptionHelpFormatter
    parser = argparse.ArgumentParser(
        description=DESCRIPTION, epilog=EPILOG,
        formatter_class=argparse.RawDescriptionHelpFormatter
    )
    
    subparsers = parser.add_subparsers(
        dest='cmd',
        title=SUBPARSER_TITLE,
        description=SUBPARSER_DESCRIPTION,
        help=SUBPARSER_HELP
    )
    
    create_parser = subparsers.add_parser('create', description=CREATE_DSCR, epilog=CREATE_HELP, formatter_class=formatter,)
    dstroy_parser = subparsers.add_parser('destroy',description=DSTROY_DSCR, epilog=DSTROY_HELP, formatter_class=formatter,)
    status_parser = subparsers.add_parser('status', description=STATUS_DSCR, epilog=STATUS_HELP, formatter_class=formatter,)
    import_parser = subparsers.add_parser('import', description=IMPORT_DSCR, epilog=IMPORT_HELP, formatter_class=formatter,)
    delete_parser = subparsers.add_parser('delete', description=DELETE_DSCR, epilog=DELETE_HELP, formatter_class=formatter,)
    search_parser = subparsers.add_parser('search', description=SEARCH_DSCR, epilog=SEARCH_HELP, formatter_class=formatter,)
    
    create_parser.set_defaults(func=publish.create_index)
    dstroy_parser.set_defaults(func=publish.dstroy_index)
    status_parser.set_defaults(func=publish.status)
    import_parser.set_defaults(func=publish.import_records)
    delete_parser.set_defaults(func=publish.delete_records)
    search_parser.set_defaults(func=publish.search)
    
    create_parser.add_argument('-H', '--host', help='Elasticsearch host and port (HOST:PORT).', **hostsarg)
    create_parser.add_argument('-i', '--index', help='Elasticsearch index.', **hostsarg)
    
    dstroy_parser.add_argument('-H', '--host', help='Elasticsearch host and port (HOST:PORT).', **hostsarg)
    dstroy_parser.add_argument('-i', '--index', help='Elasticsearch index.', **hostsarg)
    
    status_parser.add_argument('-H', '--host', help='Elasticsearch host and port (HOST:PORT).', **hostsarg)
    status_parser.add_argument('-i', '--index', help='Elasticsearch index.', **hostsarg)
    
    import_parser.add_argument('csvpath', help='Absolute path to CSV file (named ${dataset}.csv).')
    import_parser.add_argument('-d', '--dataset', required=False, help='Dataset name (if not in filename).')
    import_parser.add_argument('-H', '--host', help='Elasticsearch host and port (HOST:PORT).', **hostsarg)
    import_parser.add_argument('-i', '--index', help='Elasticsearch index.', **hostsarg)
    import_parser.add_argument('-s', '--stop', action='store_true', help='Stop if errors detected.')
    
    delete_parser.add_argument('csvpath', help='Absolute path to CSV file (named ${dataset}.csv).')
    delete_parser.add_argument('-H', '--host', help='Elasticsearch host and port (HOST:PORT).', **hostsarg)
    delete_parser.add_argument('-i', '--index', help='Elasticsearch index.', **hostsarg)
    
    search_parser.add_argument('query', help='Search query.')
    search_parser.add_argument('-H', '--host', help='Elasticsearch host and port (HOST:PORT).', **hostsarg)
    search_parser.add_argument('-i', '--index', help='Elasticsearch index.', **hostsarg)
    
    args = parser.parse_args()
    
    hosts = publish.make_hosts(args.host)
    index = publish.set_hosts_index(hosts, args.index)
    
    # call selected function
    exit = 0
    if   args.cmd == 'create':  publish.create_index(hosts, index, args)
    elif args.cmd == 'destroy': publish.dstroy_index(hosts, index, args)
    elif args.cmd == 'status':  publish.status(hosts, index, args)
    elif args.cmd == 'import':  publish.import_records(hosts, index, args)
    elif args.cmd == 'delete':  publish.delete_records(hosts, index, args)
    elif args.cmd == 'search':  publish.search(hosts, index, args)


if __name__ == '__main__':
    main()
