#! /usr/bin/env python

'''
    PURPOSE: Determine which executable to run and then pass all arguments
             through to the appropriate script.

    PROJECT: Land Satellites Data Systems Science Research and Development
             (LSRD) at the USGS EROS

    LICENSE: NASA Open Source Agreement 1.3

    NOTES:
        This script does not have its own help message and will just pass
        the help from underlying executables where appropriate.

        All output from the underlying script will be given to the logger as
        an info message.
'''

import os
import sys
import logging
import argparse
import subprocess
from configparser import ConfigParser
from espa import Sys

# Get the logger
logger = logging.getLogger(__name__)

# Local imports
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import st_utilities as util


def parse_cmd_line():
    """Will only parse --xml XML_FILENAME and --st_algorithm ALGORITHM_NAME
       from cmdline.  Other arguments are just passed through.

    Precondition:
        '--xml FILENAME' exists in command line arguments
        '--st_algorithm ALGORITHM_NAME' exists in command line arguments

    Postcondition:
        returns (xml_filename, st_algorithm)

    Note: Help is not included because the program will return the help for
          the underlying program

    """

    # Try to parse out the XML so the application can be determined
    parse_args = argparse.ArgumentParser(add_help=False)

    parse_args.add_argument('--xml', action='store',
                            dest='xml_filename', required=False,
                            help='Input XML metadata file')

    parse_args.add_argument('--st_algorithm', action='store',
                            dest='st_algorithm', required=False,
                            default='single_channel',
                            help='Surface Temperature algorithm '
                                 '(single_channel or split_window)')

    (temp, extra_args) = parse_args.parse_known_args()

    if not temp.xml_filename or not temp.st_algorithm:
        parse_args.print_help()
        exit(-1)

    return (temp.xml_filename, temp.st_algorithm)


def get_science_application_name(satellite_sensor_code, st_algorithm):
    """Returns name of executable that needs to be called
    """

    if st_algorithm == 'split_window':
        # Split window requires 2 thermal bands
        available = ['LC08', 'LT08', 'LC09', 'LT09']
    else:
        available = ['LT04', 'LT05', 'LE07', 'LC08', 'LT08', 'LC09', 'LT09']

    if satellite_sensor_code in available:
        if st_algorithm == 'single_channel':
            return 'st_generate_products.py'
        elif st_algorithm == 'split_window':
            return 'st_generate_split_window_products.py'
        else:
            raise Exception('ST algorithm name ({0}) not understood'
                            .format(st_algorithm))
    else:
        raise Exception('Satellite-Sensor code ({0}) not understood'
                        .format(satellite_sensor_code))


def main():
    """Determines executable, and calls it with all input arguments
    """

    # Setup the default logger format and level.  Log to STDOUT.

    (xml_filename, st_algorithm) = parse_cmd_line()
    Sys.setup_logging()
    satellite_sensor_code = \
        util.get_satellite_sensor_code(xml_filename.rsplit('.',1)[0])

    # Get the science application
    cmd = [get_science_application_name(satellite_sensor_code, st_algorithm)]

    # Remove any --st_algorithm arguments, since these are not used by the
    # individual Surface Temperature algorithms
    sys.argv = [x for x in sys.argv if '--st_algorithm' not in x]
    sys.argv = [x for x in sys.argv if 'split_window' not in x]
    sys.argv = [x for x in sys.argv if 'single_channel' not in x]

    # Pass the rest of the arguments through to the science application
    cmd.extend(sys.argv[1:])

    # Convert the list to a string
    cmd = ' '.join(cmd)
    try:
        logger.info(' '.join(['EXECUTING SCIENCE APPLICATION:', cmd]))
        output = Sys.execute_cmd(cmd)

        if len(output) > 0:
            logger.info('\n{0}'.format(output))
    except Exception:
        logger.exception('Error running {0}.'
                         'Processing will terminate.'
                         .format(os.path.basename(__file__)))
        raise  # Re-raise so exception message will be shown.


if __name__ == '__main__':
    main()
