#! python3
import mhrc.automation, os, logging
from win32com.shell import shell, shellcon

# Log 'INFO' messages & above.  Include level & module name.
logging.basicConfig(level=logging.INFO,
                    format="%(levelname)-8s %(name)-26s %(message)s")

# Ignore INFO msgs from automation (eg, mhrc.automation.controller, ...)
logging.getLogger('mhrc.automation').setLevel(logging.WARNING)

LOG = logging.getLogger('main')
	
# Find "Public Documents" folder
#   Probably "C:\Users\Public\Documents"
public_dir = shell.SHGetFolderPath(0, shellcon.CSIDL_COMMON_DOCUMENTS, None, 0)
LOG.info("Public Documents  : %s", public_dir)

# Find the "Tutorial" workspace
#   Probably "<Public Documents>\PSCAD\4.6.3\Examples\tutorial\Tutorial.pswx"
tutorial_dir = next(root for root, _, files in os.walk(
    os.path.join(public_dir, "PSCAD") ) if "Tutorial.pswx" in files)
LOG.info("Tutorial directory: %s", tutorial_dir)

controller = mhrc.automation.controller()
versions = controller.get_paramlist_names('pscad')
LOG.info("PSCAD Versions: %s", versions)

# Skip any 'Alpha' versions, if other choices exist
vers = [ver for ver in versions if 'Alpha' not in ver]
if len(vers) > 0:
    versions = vers

# Skip any 'Beta' versions, if other choices exist
vers = [ver for ver in versions if 'Beta' not in ver]
if len(vers) > 0:
    versions = vers

# Skip any 32-bit versions, if other choices exist
vers = [ver for ver in versions if 'x86' not in ver]
if len(vers) > 0:
    versions = vers

LOG.info("   After filtering: %s", versions)

# Of any remaining versions, choose the "lexically largest" one.
version = sorted(versions)[-1]
LOG.info("   Selected PSCAD version: %s", version)


# Get all installed FORTRAN compiler versions
fortrans = controller.get_paramlist_names('fortran')
LOG.info("FORTRAN Versions: %s", fortrans)

# Skip 'GFortran' compilers, if other choices exist
vers = [ver for ver in fortrans if 'GFortran' not in ver]
if len(vers) > 0:
    fortrans = vers

LOG.info("   After filtering: %s", fortrans)

# Order the remaining compilers, choose the last one (highest revision)
fortran = sorted(fortrans)[-1]
LOG.info("   Selected FORTRAN version: %s", fortran)


# Launch PSCAD
LOG.info("Launching: %s  FORTRAN=%r", version, fortran)
pscad = mhrc.automation.launch_pscad(pscad_version=version, minimize=True,
                                     fortran_version=fortran)

if pscad:

    try:
        # Load the tutorial workspace
        pscad.load(os.path.join(tutorial_dir, "Tutorial.pswx"))

        # Run all the simulation sets in the workspace
        pscad.run_all_simulation_sets()

    finally:
        # Exit PSCAD
        pscad.quit()

else:
    LOG.error("Failed to launch PSCAD")

