#
# 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 apex
from apex.construct import Point3D, Point2D



import os
import sys
import importlib

pathDir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))

if not pathDir in sys.path:
	sys.path.insert(0, pathDir)
	print('inserted ' + pathDir + ' into sys.path')

from utils_subprocess_v106 import *
importlib.reload(sys.modules['utils_subprocess_v106'])
from utils_subprocess_v106 import *


def main(dict={}):

	# apex.disableShowOutput()
	model_1 = apex.currentModel()

	# Dict to transfer settings regarding model specifics, such as settings per contact body, event settings et.c.
	OptionsD={}
	settings_file = dict["xml_file"]
	bdf_path = dict["bdf_path"]

	#settings_file = file_path + "/res/UtilityUserSettings.xml"
	#settings_file=

	try:
		if os.path.isfile(settings_file):
			pass
		else:
			print("Settings file not selected")
			return
	except:
		print("Something is wrong the settings file: " + settings_file + " doesn't seem to exist")
		return

	try:
		SettingsD=read_settings(settings_file)
	except:
		print("reading of Settings file failed... exit")
		return

	if type(dict['Frecuency']) == str:
		# dict['Frecuency'] = dict['Frecuency'][2:-2]
		dict['Frecuency'] = dict['Frecuency'].replace("]", "")
		dict['Frecuency'] = dict['Frecuency'].replace("[", "")
		dict['Frecuency'] = dict['Frecuency'].replace("'", "")
		dict['Frecuency'] = dict['Frecuency'].split(", ")
		dict['Frecuency'] = list(dict['Frecuency'])

	if type(dict['Magnitude']) == str:
		# dict['Magnitude'] = dict['Magnitude'][2:-2]
		dict['Magnitude'] = dict['Magnitude'].replace("'", "")
		dict['Magnitude'] = dict['Magnitude'].replace("]", "")
		dict['Magnitude'] = dict['Magnitude'].replace("[", "")
		dict['Magnitude'] = dict['Magnitude'].split(", ")
		dict['Magnitude'] = list(dict['Magnitude'])

	SettingsD['NASTRAN_JOB_SETUP']['RANDOMPSD_Frec'] = []
	SettingsD['NASTRAN_JOB_SETUP']['RANDOMPSD_Mag'] = []
	SettingsD['NASTRAN_JOB_SETUP']['RANDOMPSD_Frec'].extend(dict['Frecuency'])
	SettingsD['NASTRAN_JOB_SETUP']['RANDOMPSD_Mag'].extend(dict['Magnitude'])
	SettingsD['NASTRAN_JOB_SETUP']['RunNastran'] = dict['RunNastran']

	# create a variable that we can later access
	SettingsD['System']['SettingsFile']=settings_file

	Scenario = dict["Scenario"]

	if bdf_path=="":
		print("***Warning***No export filename given")
		return


	#====Analysis Options ==================

	AnalysisType = "Nastran SOL111"
	exportOptionFlag = "RANDOM"

	try:
		export_units=SettingsD['System']['ExportUnitSystem']
	except:
		print("Could not obtain default units from settings file")
		return

	#Not supported set up for Patran yet
	hierarchy_flag=False

	# try to retrieve Scenario from Name, export bdf
	study = apex.getPrimaryStudy()
	scenario1 = study.getScenario( name = Scenario )
	scenario1.exportFEModel(
		filename = bdf_path,
		unitSystem = export_units,
		exportWideFormat = False,
		exportHierarchicalFiles = hierarchy_flag,
		resultOutputType = apex.attribute.NastranResultOutputType.Hdf5,
		renumberMethod = apex.attribute.ExportRenumberMethod.Internal,
		apexEngineeringAbstractions = False,
	)
	# SettingsD['NASTRAN_JOB_SETUP']['RunNastran'] = "True"

	ProcessSettingsFileOptions(bdf_path,SettingsD,exportOptionFlag,OptionsD)


	print("Done exporting")




##main()
