"""
Example of how to use SimAuto methods in Python
Developed by PowerWorld 2019, created by Mayank Hirani

Script #1: Basic setup and case actions
Includes:
    OpenCase()
    GetCaseHeader()
    RunScriptCommand()
    CloseCase()
"""

# Specify file path to test case
file_name = "C:\\Training Cases\\B7FLAT.pwb" # Set this to a path on your system

# Import file path tools
import os

# Import the win32com library to connect to SimAuto
import win32com.client
SimAuto = win32com.client.Dispatch("pwrworld.SimulatorAuto")

# Open the case using the file path
(err,) = SimAuto.OpenCase(file_name)
if err:
    raise Exception(f'Error: {err}')
else:
    print(f'Opened {os.path.basename(file_name)}')

# Print the case header, which includes the description of the case, using
# the GetCaseHeader() method
(err, header) = SimAuto.GetCaseHeader(file_name)
if err:
    raise Exception(f'Error: {err}')
else:
    print('Case Header:')
    print('\t', header)

# Run the power flow
(err,) = SimAuto.RunScriptCommand('SolvePowerFlow')
if err:
    raise Exception(f'Error: {err}')
else:
    print('Solved Power Flow')

# Save a copy of the solved case
path = os.path.splitext(file_name)
new_name = f'{path[0]}_new{path[1]}'
(err,) = SimAuto.SaveCase(new_name, 'PWB', True)
if err:
    raise Exception(f'Error: {err}')
else:
    print(f'Saved as {os.path.basename(new_name)}')

# Close the case
(err,) = SimAuto.CloseCase()
if err:
    raise Exception(f'Error: {err}')
else:
    print("Closed Case")

# Disconnect
SimAuto = None

# A full list of the script commands that can be run using RunScriptCommand()
# can be found here: 
# https://www.powerworld.com/WebHelp/Content/Other_Documents/Auxiliary-File-Format.pdf
