#!/usr/bin/env python
"""
This script provides the command-line interface (CLI) to the PyReshaper

This script is designed to run a specfile (i.e., a Pickled Specifier object).
The specfile itself should be constructed from a hand-written Python script,
or from the makes2sspec tool that accompanies this script.

Copyright 2015, University Corporation for Atmospheric Research
See the LICENSE.rst file for details
"""

# Builtin Modules
import argparse
import glob
import cPickle as pickle

# Package Modules
from pyreshaper import specification
from pyreshaper import reshaper


#==============================================================================
# Command-line Interface
#==============================================================================
__DESC__ = """This tool is designed to run a PyReshaper Specifier as read
              from a pickled Specifier object (specfile)"""
__PARSER__ = argparse.ArgumentParser(description=__DESC__)
__PARSER__.add_argument('-1', '--once', default=False,
                        action='store_true', dest='once',
                        help='Whether to write a "once" file with all '
                             'metadata. [Default: False]')
__PARSER__.add_argument('-l', '--limit', default=0, type=int,
                        help='The limit on the number of time-series files per '
                        'processor to write.  Useful when debugging.  A '
                        'limit of 0 means write all output files.'
                        '[Default: 0]')
__PARSER__.add_argument('-m', '--write_mode', default='w', type=str,
                        help="Determine the write mode to use for writing "
                             "output files.  Can be 'w' for normal operation, "
                             "'s' to skip generation of time-series files if "
                             "the files already exist, 'o' to overwrite "
                             "existing time-series files, or 'a' to append "
                             "to existing time-series files [Default: 'w']")
__PARSER__.add_argument('-s', '--serial', default=False,
                        action='store_true', dest='serial',
                        help='Whether to run in serial (True) or parallel '
                             '(False). [Default: False]')
__PARSER__.add_argument('-v', '--verbosity', default=1, type=int,
                        help='Verbosity level for level of output.  A value '
                             'of 0 means no output, and a value greater than '
                             '0 means more output detail. [Default: 1]')
__PARSER__.add_argument('specfile', default=None, metavar='SPECFILE', type=str,
                        help='The Pickled Specifier (specfile) to be used as '
                             'to the PyReshaper.  [Default: None]')


#==============================================================================
# Command-line Opeartion
#==============================================================================
if __name__ == '__main__':
    args = __PARSER__.parse_args()

    print args

    # Try importing the file
    try:
        spec = pickle.load(open(args.specfile, 'rb'))
    except:
        err_msg = ("Specifier File '{}' could not be "
                   "opened and read").format(args.specfile)
        raise RuntimeError(err_msg)

    print spec

    # Create the PyReshaper object
    reshpr = reshaper.create_reshaper(spec,
                                      serial=args.serial,
                                      verbosity=args.verbosity,
                                      wmode=args.write_mode,
                                      once=args.once)

    # Run the conversion (slice-to-series) process
    reshpr.convert(output_limit=args.limit)

    # Print timing diagnostics
    reshpr.print_diagnostics()
