#!/usr/bin/env python

"""Namelist creator for CDEPS data atm 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

_CDEPS_CONFIG = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir,os.pardir,"cime_config")
_CIMEROOT = os.environ.get("CIMEROOT")
if _CIMEROOT is None:
    raise SystemExit("ERROR: must set CIMEROOT environment variable")
_LIBDIR = os.path.join(_CIMEROOT, "scripts", "Tools")
sys.path.append(_LIBDIR)
sys.path.append(os.path.join(_CDEPS_CONFIG))

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

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.
    """

    #----------------------------------------------------
    # Write out datm_in and datm.streams.xml
    #----------------------------------------------------

    caseroot = case.get_value("CASEROOT")
    datm_mode = case.get_value("DATM_MODE")
    datm_topo = case.get_value("DATM_TOPO")
    datm_presaero = case.get_value("DATM_PRESAERO")
    datm_co2_tseries = case.get_value("DATM_CO2_TSERIES")
    atm_grid = case.get_value("ATM_GRID")
    model_grid = case.get_value("GRID")
    comp_lnd = case.get_value("COMP_LND")

    # Check for incompatible options.
    if "CLM" in datm_mode and comp_lnd == "clm":
        expect(datm_presaero != "none",
               "A DATM_MODE for CLM is incompatible with DATM_PRESAERO=none.")
        expect(datm_topo != "none",
               "A DATM_MODE for CLM is incompatible with DATM_TOPO=none.")

    # Log some settings.
    logger.debug("DATM mode is {}".format(datm_mode))
    logger.debug("DATM grid is {}".format(atm_grid))
    logger.debug("DATM presaero mode is {}".format(datm_presaero))
    logger.debug("DATM topo mode is {}".format(datm_topo))

    # Initialize namelist defaults
    config = {}
    config['model_grid'] = model_grid
    config['datm_mode'] = datm_mode
    config['datm_co2_tseries'] = datm_co2_tseries
    config['datm_presaero'] = datm_presaero
    config['cime_model'] = get_model()
    config['scol_mode'] = 'true' if case.get_value('PTS_MODE') else 'false'
    config['create_mesh'] = 'true' if case.get_value("ATM_DOMAIN_MESH") == 'create_mesh' else 'false'

    nmlgen.init_defaults(infile, config)

    # Generate datm_in
    namelist_file = os.path.join(confdir, "datm_in")
    nmlgen.write_output_file(namelist_file, data_list_path, groups=['datm_nml'])

    # Determine streams
    streamlist = nmlgen.get_streams()
    print "DEBUG: streamlist is ",streamlist
    if datm_presaero != "none":
        streamlist.append("presaero.{}".format(datm_presaero))
    if datm_topo != "none":
        streamlist.append("topo.{}".format(datm_topo))
    if datm_co2_tseries != "none":
        streamlist.append("co2tseries.{}".format(datm_co2_tseries))
    bias_correct = nmlgen.get_value("bias_correct")
    if bias_correct is not None:
        streamlist.append(bias_correct)
    anomaly_forcing = nmlgen.get_value("anomaly_forcing")
    if anomaly_forcing[0] is not None:
        streamlist += anomaly_forcing
    
    # Generate datm.streams.xml
    stream_file = os.path.join(_CDEPS_CONFIG,os.pardir, "datm","cime_config","stream_definition_datm.xml")
    schema_file = os.path.join(_CDEPS_CONFIG,"streams_v2.0.xsd")
    streams = StreamCDEPS(stream_file, schema_file)
    outfile = os.path.join(confdir, "datm.streams"+inst_string+".xml" )
    streams.create_stream_xml(streamlist, case, outfile, data_list_path)

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

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

    rundir = case.get_value("RUNDIR")
    ninst = case.get_value("NINST_ATM")
    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 and namelist_defaults.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(comp_interface="nuopc")
    definition_file = [files.get_value("NAMELIST_DEFINITION_FILE", {"component":"datm"})]

    user_definition = os.path.join(user_xml_dir, "namelist_definition_datm.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, files=files)

    #----------------------------------------------------
    # Clear out old data.
    #----------------------------------------------------
    data_list_path = os.path.join(caseroot, "Buildconf", "datm.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
        copy_inputs_to_rundir(caseroot, compname, confdir, rundir, inst_string)

###############################################################################
def _main_func():
    caseroot = parse_input(sys.argv)
    with Case(caseroot) as case:
        buildnml(case, caseroot, "datm")


if __name__ == "__main__":
    _main_func()
