#!/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 atm_query_impl
from utils import expect

###############################################################################
def atm_query(variables,listall=False,full=False,value=False, \
              dtype=False, valid_values=False, grep=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,grep)

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

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

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

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

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

    \033[1;32m# print all variables whose name matches expr\033[0m
    > {0} --grep expr

""".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(
        "--grep",
        default=False,
        action="store_true",
        help="List all matching variables and their values.",
    )

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

    # The following options are mutually exclusive
    group1 = parser.add_argument_group(title="Display options")
    group2 = parser.add_mutually_exclusive_group()

    group2.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.",
    )

    group2.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.",
    )

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

    group2.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 args.grep and args.listall:
        parser.error("Cannot specify --listall and --grep at the same time")

    if args.grep and args.variables is None:
        parser.error("Option --grep requires to pass a variable regex")

    if args.variables is not None and len(args.variables)==1:
        args.variables = args.variables[0].split(",")

    return args

###############################################################################
def _main_func(description):
###############################################################################
    if "--test" in sys.argv:
        from doctest import testmod
        import atm_manip
        testmod()
        testmod(m=atm_manip)
    else:
        success = atm_query(**vars(parse_command_line(sys.argv, description)))
        sys.exit(0 if success else 1)

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

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