# 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_v106c import *
importlib.reload(sys.modules['aux_functions_v106c'])
from aux_functions_v106c import *


def importMaterialFromBdf(bdf_file,TempMatDir):

	#Read material

	model_1 = apex.currentModel()
	
	#MAT2*
	#PcompD, Mat8D, PShellD, Mat2D=read_mat_and_props(r"D:\Software\Hypersizer\LargerWing_bdf_200609_0916\Static_Scenario_Part.bdf")	
	#MAT8*
	#PcompD, Mat8D, PShellD, Mat2D=read_mat_and_props(r"D:\Software\Hypersizer\Scripts\Static_Scenario_Part.bdf")
	#MAT1, MATEP, MATTEP, MATT1, TABLES1, TABLEST, TABLEM1, PSOLID, PSLDN1
	global MxPxD
	
	MxPxD=read_mat_and_props(bdf_file)
	CLexApex.setMxPxD(MxPxD)
	for card in MxPxD:
		#print(card,MxPxD[card])
		print(card)
		for key in MxPxD[card].keys():
			print("%8d" % (key),MxPxD[card][key])
		print("========")
		
	
	# Check all PSHELLS- only read materials appearing as MID1...or MID 2 if MID1 blank... et.c.
	pshellMid1D={}
	for pid in MxPxD['PSHELL'].keys():
		if  MxPxD['PSHELL'][pid][0][16:24].strip() != "":
			pshellMid1D[pid]=int(MxPxD['PSHELL'][pid][0][16:24].strip())
		elif  MxPxD['PSHELL'][pid][0][32:40].strip() != "":
			pshellMid1D[pid]=int(MxPxD['PSHELL'][pid][0][32:40].strip()) 
		elif  MxPxD['PSHELL'][pid][0][48:54].strip() != "":
			pshellMid1D[pid]=int(MxPxD['PSHELL'][pid][0][48:54].strip())
		elif  MxPxD['PSHELL'][pid][0][-8:].strip() != "":
			pshellMid1D[pid]=int(MxPxD['PSHELL'][pid][0][-8:].strip())
	
	#get Mat
	# get MAT1's and assiciated MATX and TABX cards
	
	for mat1_id in MxPxD['MAT1'].keys():
		m1=material(MxPxD['MAT1'][mat1_id][0])
		#try:
		if 1==1:
			#try using SXNAME 
			print("MxPxD['MAT1'][mat1_id]")
			print(MxPxD['MAT1'][mat1_id])
			try:
				mat_name=MxPxD['MAT1'][mat1_id][2]
				print(mat_name)
				m1.name=mat_name
			except:
				mat_name='MAT1'
		#except:
		#	print("No name")
			
		#m1.writeMatToTempFile(r"C:\Users\e7390\Documents\MSC_Apex Workspace\JaguarUtils\TmpMaterials")
		#m1.writeMatToTempFile(r"D:\Software\Apex\MaterialMethods\TmpMaterials")
		m1.writeMatToTempFile(TempMatDir)
		
	for mat1_id in MxPxD['MAT2'].keys():
		
		# Check so that affected MAT2 appears as first MID in PSHELL
		for pid in pshellMid1D.keys():
			if pshellMid1D[pid]==mat1_id:
				print("Found a material:",mat1_id)
				m2=material(MxPxD['MAT2'][mat1_id][0],prop_ids=[pid])
				m2.writeMatToTempFile(TempMatDir)
				
		
		
	for mat1_id in MxPxD['MAT8'].keys():
		m8=material(MxPxD['MAT8'][mat1_id][0])
		#m1.writeMatToTempFile(r"C:\Users\e7390\Documents\MSC_Apex Workspace\JaguarUtils\TmpMaterials")
		#m1.writeMatToTempFile(r"D:\Software\Apex\MaterialMethods\TmpMaterials")
		m8.writeMatToTempFile(TempMatDir)	
		
	
	return 
	

	

def main(dict={}):
	import time
	import cProfile,pstats, io
	pr = cProfile.Profile()	
	pr.enable()

	startTime = time.process_time()



	apex.enableShowOutput()
	model_1 = apex.currentModel()
	
	settings_file=dict["xml_file"] 
	bdf_file=dict["bdf_file"]
	settings_file=dict["xml_file"]
	
	# create a variable that we can later access	
	
	
	#global MxPxD
	# read Settings from xml- overwrite with GUI input where applicable
	#try:
	if 1==1:
		if os.path.isfile(settings_file):
			print("Read settings file:", settings_file )
			SettingsD=read_settings(settings_file)
			SettingsD['System']['SettingsFile']=settings_file
			if 1==1:
				print(SettingsD.keys())
				TempMatDir=SettingsD['System']['MaterialDatabaseTempDir']
				
				
				TempMatDir=resolve_pathname(TempMatDir,settings_file)
				print("TempMatDir",TempMatDir)

						
				print("Created Temp material directory: ",TempMatDir )
			#except:
			#	print("SettingsD['System']['MaterialDatabaseTempDir'] can not be found")
			#	return

		else:
			print("Settings file not existing or not selected")
			return	
	
	
	# Check if bdf file exists
	#try:
	if 1==1:
		if os.path.isfile(bdf_file):
			print("Bdf file:", bdf_file )
			# import bdf, extract materials, write back to tmp file
			MaterialD=importMaterialFromBdf(bdf_file,TempMatDir)			
			pass
		else:
			print("Bdf file not selected")
			return
	#except:
	#	print("Something is wrong with the bdf file: " + bdf_file + " doesn't seem to exist or can not be opened")
	#	return	
		
	
	#Create material model from imported materials
	if 1==1:
		MaterialD=readMaterialsFromFile(SettingsD,TmpMat=True)
		
		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
			#mat1_ids=MxPxD['MAT1'].keys()
			
				
			#for card in MxPxD:
			#	print(card,MxPxD[card])
			#	print("========")
				
			_tmp_descriptor="Placeholder Mat1. Export Utils tool will convert to material model with following cards:\n"
			for card in MxPxD:
				#print(card,MxPxD[card])
				print(card,":")
				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, "	
					
				#for key in MxPxD[card].keys():
				#	print(MxPxD[card][key])
				#	_tmp_descriptor+=str(MxPxD[card][key]) + "\n"
				print("========")		
			
			
			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")
					m1.descriptor=_tmp_descriptor
					#print("TmpDescriptor:",_tmp_descriptor,"EndDescriptor")
					m1.createApexIsotropic()

					print( dir(m1) )
			

			if len(MxPxD['MAT2']) > 0:
				try:
					pids=list(MxPxD['PSHELL'].keys())
				except:
					pids=[]
					print("no pshells found")
						
					
				for mat1_id in MxPxD['MAT2'].keys():
					print("===MAT2===")
					#print(MxPxD['MAT2'][mat1_id][0])
					if pids != []:
						m2=material(MxPxD['MAT2'][mat1_id][0],pids)
						# check if m2 has a pshell associated
						GoFlag=False
						try:
							print("Found mid1",m2.mid1Id)
							if m2.mid1Id==m2.id:
								GoFlag=True
						except:
							print("Not Mid1")
							
						if GoFlag:
							print("Creating Apex placeholder material")
							m2.descriptor=_tmp_descriptor
							##print("TmpDescriptor:",_tmp_descriptor,"EndDescriptor")
							m2.createApexIsotropic()
						

						# try:
							# print("*** test pshell ***")
							# print( dir(m2.pshell))
							
							# print((m2.mid1Id))
							# #print(m2.pshell.mid2)
							# #print(m2.pshell.mid3)
							# #print(m2.pshell.mid4)
						# except:
							# print("** *No pshell ***")
						#print("Creating Apex placeholder material")
						#m2.descriptor=_tmp_descriptor
						##print("TmpDescriptor:",_tmp_descriptor,"EndDescriptor")
						#m2.createApexIsotropic()

						#print( dir(m2) )
				
			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")
					m8.descriptor=_tmp_descriptor
					#print("TmpDescriptor:",_tmp_descriptor,"EndDescriptor")
					m8.createApexOrtotropic()

					print( dir(m8) )	
				
				
			
			#elif len(MxPxD['MAT1']) ==0:
			#	print("No MAT1s...need to check...")
				
			else:
				print("Warning : Multiple MAT1s are not supported")
	

		

	print("Done Import")

	pr.disable()
	s = io.StringIO()
	sortby = 'cumulative'
	ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
	ps.print_stats()
	print(s.getvalue())
	

##main()


