#!/usr/bin/python

import os
import sys
import argparse

import baip_loader

CONF = os.path.join(os.sep, 'etc', 'baip', 'conf', 'loader.conf')
DESCRIPTION = """BAIP CSIRO Mapper Tool"""


def main():
    """Script entry point.

    """
    parser = argparse.ArgumentParser(description=DESCRIPTION)
    parser.add_argument('-c',
                        '--config-file',
                        action='store',
                        dest='config_file')

    # Add sub-command support.
    subparsers = parser.add_subparsers(help='commands')

    # 'scrape' subcommand.
    scrape_help = 'Pull data from CSIRO endpoint'
    scrape_parser = subparsers.add_parser('scrape', help=scrape_help)
    scrape_parser.set_defaults(func=scrape)

    infile_help = 'Source XML from filename'
    scrape_parser.add_argument('-i',
                               '--input-file',
                               action='store',
                               help=infile_help,
                               dest='infile')

    outfile_help = 'Override output filename'
    scrape_parser.add_argument('-o',
                               '--outfile',
                               action='store',
                               help=outfile_help,
                               dest='outfile')

    # 'map' subcommand.
    xlate_help = 'Map CSIRO XML to JSON'
    xlate_parser = subparsers.add_parser('map', help=xlate_help)
    xlate_parser.set_defaults(func=xlate)

    infile_help = 'Source XML from filename'
    xlate_parser.add_argument('-i',
                              '--input-file',
                              action='store',
                              help=infile_help,
                              dest='infile')

    # 'dump' subcommand.
    dump_help = 'Dump CSIRO XML as individual JSON files'
    dump_parser = subparsers.add_parser('dump', help=dump_help)
    dump_parser.set_defaults(func=dump)

    infile_help = 'Source XML from filename'
    dump_parser.add_argument('-i',
                             '--input-file',
                             action='store',
                             help=infile_help,
                             dest='infile')

    # 'ingest' sub-command
    ingest_help = 'Ingest CKAN JSON files'
    ingest_parser = subparsers.add_parser('ingest', help=ingest_help)
    ingest_parser.set_defaults(func=ingest)

    infile_help = 'Source XML from filename'
    ingest_parser.add_argument('-i',
                               '--input-file',
                               action='store',
                               help=infile_help,
                               dest='infile')

    dry_help = 'Ingest dry pass'
    ingest_parser.add_argument('-d',
                               '--dry',
                               action='store_true',
                               help=dry_help,
                               dest='dry')

    # Prepare the argument list and config.
    args = parser.parse_args()

    config_file = args.config_file
    if args.config_file is None:
        if os.path.exists(CONF):
            config_file = CONF

    if config_file is None:
        sys.exit('Unable to source the BAIP loader.conf')

    conf = baip_loader.LoaderConfig(config_file)
    conf.parse_config()

    args.func(args, conf)


def scrape(args, conf):
    loader = baip_loader.Loader()
    loader.csiro_source_uri = conf.csiro_uri

    loader.source(filename=args.infile)
    if args.outfile is not None:
        loader.dump_source(args.outfile)
    else:
        loader.dump_source('csiro_metadata.xml')


def xlate(args, conf):
    mapper = baip_loader.Mapper(target_dir=conf.inbound_dir)
    mapper.loader.ckan_mapper = conf.ckan_mapper
    mapper.loader.validation_sets = conf.validation_sets
    mapper.loader.ckan_defaults = conf.ckan_defaults
    mapper.xml_to_ckan_map(uri=conf.csiro_uri, infile=args.infile)


def dump(args, conf):
    dumper = baip_loader.Dumper()
    dumper.target_dir = conf.inbound_dir
    dumper.dump(uri=conf.ckan_uri, infile=args.infile)


def ingest(args, conf):
    ingester = baip_loader.Ingester(conf.inbound_dir)
    ingester.api_key = conf.ckan_api_key
    ingester.ckan_uri = conf.ckan_uri

    files_to_process = []
    if args.infile is not None:
        files_to_process.append(args.infile)
    else:
        files_to_process = ingester.source_files(file_filter='.*\.json')

    for file_to_process in files_to_process:
        with open(file_to_process, 'r') as json_fh:
            json_data = json_fh.read()
            ingester.ingest(json_data, args.dry)

if __name__ == '__main__':
    main()
