#
# Copyright © 2020 MSC.Software Corporation
#  
# Permission to use Scripts
#  
# Permission is granted to MSC.Software customers with valid licenses of the MSC Apex™ software 
# to use script files posted on this page (collectively “Scripts”) solely for customers’ own authorized 
# internal use in conjunction with licensed use of the MSC Apex software.  
# No other use is permitted.  No license to MSC Apex or other software is granted under this Permission.
#  
# SCRIPTS ARE PROVIDED ON AN "AS-IS" BASIS, WITH NO WARRANTIES OF ANY KIND.  USE OF THE SCRIPTS IS AT CUSTOMER'S SOLE RISK.
#  
# IN NO EVENT SHALL MSC.SOFTWARE CORPORATION, ITS AFFILIATES, SUBSIDIARIES, SUPPLIERS, AGENTS, REPRESENTATIVES OR EMPLOYEES BE LIABLE FOR ANY 
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, 
# STRICT LIABILITY, OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION USE OF THE SCRIPTS, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  
#  
# Customer shall indemnify, defend and hold MSC.Software Corporation, its affiliates, subsidiaries, suppliers, agents, 
# employees or representatives (collectively, “Indemnified Parties”) harmless from and against any third-party claims 
# brought against Indemnified Parties rising out of or in connection with Customer’s use of the Scripts.
#
import os
import sys
import subprocess

import System
import Microsoft.Win32 as Win32


def msg(s):
    System.Windows.MessageBox.Show(s)
    
    
def getDefaultEnvironment( ):
    envPath = ""
    
    try:
        key = Win32.RegistryKey.OpenBaseKey(Win32.RegistryHive.CurrentUser, Win32.RegistryView.Default)
        if key is not None:
            envKey = key.OpenSubKey("Environment")
            if envKey is not None:
                value = envKey.GetValue("PATH")

                if value is not None:
                    envPath += str(value)

                envKey.Dispose()

            key.Dispose()

        keyLocal = Win32.RegistryKey.OpenBaseKey(Win32.RegistryHive.LocalMachine, Win32.RegistryView.Default)
        if keyLocal is not None:
            envLocal = keyLocal.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment")
            if envLocal is not None:
                value = envLocal.GetValue("PATH")

                if value is not None:
                   envPath += ";" + str(value) 

                envLocal.Dispose()

            keyLocal.Dispose()
    except System.Exception:
        pass
    except:
        pass

    return envPath


def getCAEfatiguePathFromRegistry( ):

    path = None 

    latestVersion = getRegistryValue("Software\\MSC.Software Corporation\\CAEfatigue\\Latest", None)
    if latestVersion is not None:
        path = getRegistryValue("Software\\MSC.Software Corporation\\CAEfatigue\\" + latestVersion, "path")                        
    
    return path


def getRegistryValue(path, name):
    value = None
    
    try:
        key = Win32.RegistryKey.OpenBaseKey(Win32.RegistryHive.LocalMachine, Win32.RegistryView.Registry32)

        currentVersionKey = key.OpenSubKey(path)
        if currentVersionKey is not None:
            value = currentVersionKey.GetValue(name)              
            currentVersionKey.Dispose()
            
        key.Dispose()
    except:
        pass

    return value


def runProgram(programPath, programArguments, workingDirectory = None):
    result = 255
    
    process = System.Diagnostics.Process()
    process.StartInfo.FileName = programPath
    process.StartInfo.Arguments = programArguments
    process.StartInfo.UseShellExecute = False
    
    try:
        path = getDefaultEnvironment()

        if path is not None:
            process.StartInfo.EnvironmentVariables["PATH"] = path

        process.Start()

        result = 0
    except System.Exception as e:
        msg(e.Message)

    return result


def runCAEfatigue(path, file = None):

    arguments = ""

    if file is not None:
        arguments += '"' + file + '"'
        
    runProgram(path + os.sep + "Windows" + os.sep + "ProcessApp.exe", arguments)


def cfgetScriptPath():
    path = os.path.dirname(os.path.realpath(__file__))
    return path
