#!/usr/bin/env python3

"""
Change a runtime parameter for SCREAM/atm. Run from your case
after case.setup.
"""

import argparse, sys, pathlib, os
import xml.etree.ElementTree as ET

# Add path to cime_config folder
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "cime_config"))
sys.path.append(os.path.dirname(os.path.realpath(__file__)))

from eamxx_buildnml_impl import check_value
from atm_manip import expect, get_xml_node, AmbiguousName, atm_query_impl

###############################################################################
def atm_query(variables,listall=False,full=False,value=False, \
              dtype=False, valid_values=False):
###############################################################################
    expect(os.path.exists("namelist_scream.xml"),
           "No pwd/namelist_scream.xml file is present. Please rum from a case dir that has been setup")

    with open("namelist_scream.xml", "r") as fd:
        tree = ET.parse(fd)
        xml_root = tree.getroot()

    return atm_query_impl(xml_root,variables,listall,full,value,dtype,valid_values)

###############################################################################
def parse_command_line(args, description):
###############################################################################
    parser = argparse.ArgumentParser(
        usage="""\n{0} [--listall] [--value] [--type] [--valid-values] [--full] [var1 [,var2 ...]
OR
{0} --help

\033[1mEXAMPLES:\033[0m
    \033[1;32m# List all settings as VAR=VALUE
    > {0} --listall

    \033[1;32m# print var1 and var2
    > {0} var1 var2

    \033[1;32m# print var1 and var2, with full details
    > {0} var1 var2 --full

    \033[1;32m# print var1 type and valid values
    > {0} var1 --type --valid-values

""".format(pathlib.Path(args[0]).name),
        description=description,
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )

    parser.add_argument(
        "variables",
        nargs="*",
        help="Variable name(s) to query from namelist_scream.xml file\n"
        "Multiple variables can be given, separated by commas or spaces.\n",
    )

    parser.add_argument(
        "--listall",
        default=False,
        action="store_true",
        help="List all variables and their values.",
    )

    # The following options are mutually exclusive
    group = parser.add_mutually_exclusive_group()

    group.add_argument(
        "--full",
        default=False,
        action="store_true",
        help="Print a full listing for each variable, including value, type,\n"
        "valid values, description and file.",
    )

    group.add_argument(
        "--value",
        default=False,
        action="store_true",
        help="Only print one value without newline character.\n"
        "If more than one has been found print first value in list.",
    )

    group.add_argument(
        "--type",
        default=False,
        action="store_true",
        help="Print the data type associated with each variable.",
    )

    group.add_argument(
        "--valid-values",
        default=False,
        action="store_true",
        help="Print the valid values associated with each variable, if defined.",
    )

    args = parser.parse_args(args[1:])

    if len(args.variables) == 1:
        variables = args.variables[0].split(",")
    else:
        variables = args.variables

    return (
        variables,
        args.listall,
        args.full,
        args.value,
        args.type,
        args.valid_values,
    )

###############################################################################
def _main_func(description):
###############################################################################
    if "--test" in sys.argv:
        from doctest import testmod
        import atm_manip
        testmod()
        testmod(m=atm_manip)
    else:
        (
            variables,
            listall,
            value,
            full,
            dtype,
            valid_values,
        ) = parse_command_line(sys.argv, description)
        success = atm_query(variables,listall,value,full,dtype,valid_values)
        sys.exit(0 if success else 1)

###############################################################################

if (__name__ == "__main__"):
    _main_func(__doc__)
