#!/usr/bin/env python

"""Namelist creator for ww3
"""

# 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, shutil, sys, glob

CIMEROOT = os.environ.get("CIMEROOT")
if CIMEROOT is None:
    raise SystemExit("ERROR: must set CIMEROOT environment variable")
sys.path.append(os.path.join(CIMEROOT, "scripts", "Tools"))

from standard_script_setup import *
from CIME.case import Case
from CIME.nmlgen import NamelistGenerator
from CIME.utils import expect
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):
####################################################################################
    """Write out the namelist for this component."""

    srcroot = case.get_value("SRCROOT")
    caseroot = case.get_value("CASEROOT")

    #----------------------------------------------------
    # Construct the namelist generator
    #----------------------------------------------------
    namelist_xml_dir = os.path.join(srcroot, "components", "ww3", "cime_config")
    definition_file = [os.path.join(namelist_xml_dir, "namelist_definition_ww3.xml")]
    nmlgen = NamelistGenerator(case, definition_file)
    infile = []

    #----------------------------------------------------
    # Create config dictionary
    #----------------------------------------------------
    config = {}
    runtype = case.get_value("RUN_TYPE")
    config["runtype"] = runtype

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

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

    run_type = case.get_value("RUN_TYPE")
    if run_type == 'branch':
        run_refcase = case.get_value("RUN_REFCASE")
        run_refdate = case.get_value("RUN_REFDATE")
        run_tod     = case.get_value("RUN_REFTOD")
        filename = "%s.ww3.r.%s-%s" %(run_refcase, run_refdate, run_tod)
        nmlgen.add_default("initfile", value=filename, ignore_abs_path=True)
    else:
        nmlgen.add_default("initfile")

    # write diagnostic info
    logger.debug("ww3 initial conditions file is %s" %nmlgen.get_value("initfile"))

    #----------------------------------------------------
    # Write output namelist
    #----------------------------------------------------
    namelist_file = os.path.join(caseroot, "CaseDocs", "wav_in")
    nmlgen.write_output_file(namelist_file, data_list_path, groups=["ww3_inparm"])

    #----------------------------------------------------
    # Prestage necessary files to rundir
    #----------------------------------------------------
    rundir = case.get_value("RUNDIR")
    din_loc_root = case.get_value("DIN_LOC_ROOT")

    file1 = os.path.join(din_loc_root,"wav","ww3","core2_G4_wns_30min_20000601_to_05.nc")
    file2 = os.path.join(rundir,"wind.ww3")
    if os.path.isfile(file1):
        shutil.copy(file1, file2)

    file1 = os.path.join(din_loc_root,"wav","ww3","G4L1.mod_def.ww3.121031")
    file2 = os.path.join(rundir,"mod_def.ww3")
    if os.path.isfile(file1):
        shutil.copy(file1, file2)

###############################################################################
def _main_func():
###############################################################################

    # Build the component namelist

    caseroot = parse_input(sys.argv)

    with Case(caseroot) as case:
        ninst = case.get_value("NINST_WAV")
        if ninst > 1:
            expect(False, "WW3 does not have multi instance functionality yet")

        _create_namelists(case)

        # copy namelist files to rundir
        # TODO: need to add multi-instance support
        rundir = case.get_value("RUNDIR")
        file1 = os.path.join(caseroot, "CaseDocs", "wav_in")
        file2 = os.path.join(rundir, "wav_in")
        shutil.copy(file1, file2)

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

if __name__ == "__main__":
    _main_func()

