#! 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)

# Launch PSCAD
pscad = mhrc.automation.launch_pscad(minimize=True)

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

