# coding: utf-8
#
# 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

apex.setScriptUnitSystem(unitSystemName = r'''mm-kg-s-N-K''')

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

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


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

def main(dict={}):
	apex.disableShowOutput()
	model_1 = apex.currentModel()
	
	settings_file=dict["xml_file"] 
	readMaterialsFlag=dict["ReadMaterials"]
	readTempMaterialsFlag=dict["ReadTempMaterials"]
	
	# create a variable that we can later access	
	print("readMaterialsFlag",readMaterialsFlag)
	print("readTempMaterialsFlag",readTempMaterialsFlag)
	
	#global MxPxD
	# read Settings from xml- overwrite with GUI input where applicable
	MaterialD={}

	try:
		if os.path.isfile(settings_file):
			print("Read settings file:", settings_file )
			SettingsD=read_settings(settings_file)
			SettingsD['System']['SettingsFile']=settings_file
			
			if readMaterialsFlag=="True":	
				Material1D=readMaterialsFromFile(SettingsD,TmpMat=False)
				
				for mat in Material1D:
					MaterialD[mat]=Material1D[mat]

			if readTempMaterialsFlag=="True":	
				Material2D=readMaterialsFromFile(SettingsD,TmpMat=True)
				for mat in Material2D:
					if mat not in MaterialD:
						MaterialD[mat]=Material2D[mat]
	except:
		print("Unable to read material folders specified in Settings file, Please check the paths")
		return	
	
	#Create material model from imported materials
	if 1==1:

		for material_name in MaterialD.keys():
			print("===========================================================================")
			print("Processing: ",material_name)
			
			#material_name='MAT1_1'
			MxPxD=MaterialD[material_name]
			CLexApex.setMxPxD(MxPxD)
			# Check so there is exactly one MAT1 card
		
			_tmp_descriptor="Placeholder Mat1. Export Utils tool will convert to material model with following cards:\n"
			for card in MxPxD:

				if len(MxPxD[card].keys()) == 1:
					_tmp_descriptor+= str(len(MxPxD[card].keys())) + " " + card + ", "
				elif len(MxPxD[card].keys()) > 1:
					_tmp_descriptor+= str(len(MxPxD[card].keys())) + " " + card + "'s, "		
			
			if len(MxPxD['MAT1']) ==1:
				for mat1_id in MxPxD['MAT1'].keys():
					m1=material(MxPxD['MAT1'][mat1_id][0])
					# get material name from bdf file
					m1.name=material_name
					
					print("Creating Apex placeholder material",material_name)
					m1.descriptor=_tmp_descriptor
					#print("TmpDescriptor:",_tmp_descriptor,"EndDescriptor")
					m1.createApexIsotropic()
			

			if len(MxPxD['MAT2']) > 0:
				for mid in MxPxD['MAT2'].keys():
					#try to get PSHELL
					try:
						psh_id=list(MxPxD['PSHELL'].keys())[0]
					except:
						psh_id=""
				
					if  psh_id != "":
						mid1Id=int(MxPxD['PSHELL'][psh_id][0][16:24])
						if int(MxPxD['MAT2'][mid][0][8:24]) == mid1Id:
							#print(MxPxD['MAT2'][mat1_id][0])
							m2=material(MxPxD['MAT2'][mid][0])
							m2.name=material_name
							print("Creating Apex placeholder material",material_name)
							m2.descriptor=_tmp_descriptor
							#print("TmpDescriptor:",_tmp_descriptor,"EndDescriptor")
							m2.createApexIsotropic()
							break

				
			if len(MxPxD['MAT8']) ==1:
				for mat1_id in MxPxD['MAT8'].keys():
					print("===MAT8===")
					print(MxPxD['MAT8'][mat1_id][0])
					m8=material(MxPxD['MAT8'][mat1_id][0])
					print("Creating Ortotropic material",material_name)
					m8.descriptor=_tmp_descriptor
					#print("TmpDescriptor:",_tmp_descriptor,"EndDescriptor")
					m8.createApexOrtotropic()
			

	print("Done Import")


	

##main()


