#!/usr/bin/env python

"""Namelist creator for CIME's data river model.
"""

# Typically ignore this.
# pylint: disable=invalid-name

# Disable these because this is our standard setup
# pylint: disable=wildcard-import,unused-wildcard-import,wrong-import-position

import os, sys, glob

_CIMEROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..","..","..","..","..")
sys.path.append(os.path.join(_CIMEROOT, "scripts", "Tools"))

from standard_script_setup import *
from CIME.case import Case
from CIME.XML.files import Files
from CIME.nmlgen import NamelistGenerator
from CIME.utils import expect, safe_copy
from CIME.buildnml import create_namelist_infile, parse_input

logger = logging.getLogger(__name__)

# pylint: disable=too-many-arguments,too-many-locals,too-many-branches,too-many-statements
####################################################################################
def _create_namelists(case, confdir, inst_string, infile, nmlgen, data_list_path):
####################################################################################
    """Write out the namelist for this component.

    Most arguments are the same as those for `NamelistGenerator`. The
    `inst_string` argument is used as a suffix to distinguish files for
    different instances. The `confdir` argument is used to specify the directory
    in which output files will be placed.
    """

    #----------------------------------------------------
    # Get a bunch of information from the case.
    #----------------------------------------------------
    rof_domain_file = case.get_value("ROF_DOMAIN_FILE")
    rof_domain_path = case.get_value("ROF_DOMAIN_PATH")
    drof_mode = case.get_value("DROF_MODE")
    rof_grid = case.get_value("ROF_GRID")

    #----------------------------------------------------
    # Check for incompatible options.
    #----------------------------------------------------
    expect(rof_grid != "null",
           "ROF_GRID cannot be null")
    expect(drof_mode != "NULL",
           "DROF_MODE cannot be NULL")

    #----------------------------------------------------
    # Log some settings.
    #----------------------------------------------------
    logger.debug("DROF mode is {}".format(drof_mode))
    logger.debug("DROF grid is {}".format(rof_grid))

    #----------------------------------------------------
    # Create configuration information.
    #----------------------------------------------------
    config = {}
    config['rof_grid'] = rof_grid
    config['drof_mode'] = drof_mode

    #----------------------------------------------------
    # Initialize namelist defaults
    #----------------------------------------------------
    nmlgen.init_defaults(infile, config)

    #----------------------------------------------------
    # Construct the list of streams.
    #----------------------------------------------------
    streams = nmlgen.get_streams()

    #----------------------------------------------------
    # For each stream, create stream text file and update
    # shr_strdata_nml group and input data list.
    #----------------------------------------------------
    for stream in streams:

        # Ignore null values.
        if stream is None or stream in ("NULL", ""):
            continue

        inst_stream = stream + inst_string
        logger.debug("DROF stream is {}".format(inst_stream))
        stream_path = os.path.join(confdir, "drof.streams.txt." + inst_stream)
        nmlgen.create_stream_file_and_update_shr_strdata_nml(config, case.get_value("CASEROOT"), stream, stream_path, data_list_path)

    #----------------------------------------------------
    # Create `shr_strdata_nml` namelist group.
    #----------------------------------------------------
    # set per-stream variables
    nmlgen.create_shr_strdata_nml()

    # Determine model domain filename (in drof_in)
    if "CPLHIST" in drof_mode:
        drof_cplhist_domain_file = case.get_value("DROF_CPLHIST_DOMAIN_FILE")
        if drof_cplhist_domain_file == 'null':
            logger.info("   ....  Obtaining DROF model domain info from first stream file: {}".format(streams[0]))
        else:
            logger.info("   ....  Obtaining DROF model domain info from stream {}".format(streams[0]))
        nmlgen.add_default("domainfile", value=drof_cplhist_domain_file)
    else:
        if rof_domain_file != "UNSET":
            full_domain_path = os.path.join(rof_domain_path, rof_domain_file)
            nmlgen.add_default("domainfile", value=full_domain_path)
        else:
            nmlgen.add_default("domainfile", value="null")

    #----------------------------------------------------
    # Finally, write out all the namelists.
    #----------------------------------------------------
    namelist_file = os.path.join(confdir, "drof_in")
    nmlgen.write_output_file(namelist_file, data_list_path, groups=['drof_nml','shr_strdata_nml'])

###############################################################################
def buildnml(case, caseroot, compname):
###############################################################################

    # Build the component namelist and required stream txt files
    if compname != "drof":
        raise AttributeError

    rundir = case.get_value("RUNDIR")
    ninst = case.get_value("NINST_ROF")
    if ninst is None:
        ninst = case.get_value("NINST")
    # Determine configuration directory
    confdir = os.path.join(caseroot,"Buildconf",compname + "conf")
    if not os.path.isdir(confdir):
        os.makedirs(confdir)

    #----------------------------------------------------
    # Construct the namelist generator
    #----------------------------------------------------
    # determine directory for user modified namelist_definitions.xml
    user_xml_dir = os.path.join(caseroot, "SourceMods", "src." + compname)
    expect (os.path.isdir(user_xml_dir),
            "user_xml_dir {} does not exist ".format(user_xml_dir))

    # NOTE: User definition *replaces* existing definition.
    files = Files()
    definition_file = [files.get_value("NAMELIST_DEFINITION_FILE", {"component":"drof"})]

    user_definition = os.path.join(user_xml_dir, "namelist_definition_drof.xml")
    if os.path.isfile(user_definition):
        definition_file = [user_definition]
    for file_ in definition_file:
        expect(os.path.isfile(file_), "Namelist XML file {} not found!".format(file_))

    # Create the namelist generator object - independent of instance
    nmlgen = NamelistGenerator(case, definition_file)

    #----------------------------------------------------
    # Clear out old data.
    #----------------------------------------------------
    data_list_path = os.path.join(case.get_case_root(), "Buildconf",
                                  "drof.input_data_list")
    if os.path.exists(data_list_path):
        os.remove(data_list_path)

    #----------------------------------------------------
    # Loop over instances
    #----------------------------------------------------
    for inst_counter in range(1, ninst+1):
        # determine instance string
        inst_string = ""
        if ninst > 1:
            inst_string = '_' + "{:04d}".format(inst_counter)

        # If multi-instance case does not have restart file, use
        # single-case restart for each instance
        rpointer = "rpointer." + compname
        if (os.path.isfile(os.path.join(rundir,rpointer)) and
            (not os.path.isfile(os.path.join(rundir,rpointer + inst_string)))):
            safe_copy(os.path.join(rundir, rpointer),
                      os.path.join(rundir, rpointer + inst_string))

        inst_string_label = inst_string
        if not inst_string_label:
            inst_string_label = "\"\""

        # create namelist output infile using user_nl_file as input
        user_nl_file = os.path.join(caseroot, "user_nl_" + compname + inst_string)
        expect(os.path.isfile(user_nl_file),
               "Missing required user_nl_file {} ".format(user_nl_file))
        infile = os.path.join(confdir, "namelist_infile")
        create_namelist_infile(case, user_nl_file, infile)
        namelist_infile = [infile]

        # create namelist and stream file(s) data component
        _create_namelists(case, confdir, inst_string, namelist_infile, nmlgen, data_list_path)

        # copy namelist files and stream text files, to rundir
        if os.path.isdir(rundir):
            filename = compname + "_in"
            file_src  = os.path.join(confdir, filename)
            file_dest = os.path.join(rundir, filename)
            if inst_string:
                file_dest += inst_string
            safe_copy(file_src,file_dest)

            for txtfile in glob.glob(os.path.join(confdir, "*txt*")):
                safe_copy(txtfile, rundir)

###############################################################################
def _main_func():
    # Build the component namelist and required stream txt files
    caseroot = parse_input(sys.argv)
    with Case(caseroot) as case:
        buildnml(case, caseroot, "drof")

if __name__ == "__main__":
    _main_func()
