# 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 math
import time
import sys
import os
from operator import itemgetter

#apex.setScriptUnitSystem(unitSystemName = r'''in-slinch-s-lbf''')
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')	



def createAndAssignSection(face,id=1,prefix="Section_",t=1.0,offs=0.0):
	SectionName=prefix+str(id)
	
	# need a mechanism to check the original thickness
	# get the elements, make sure they have same thickness
	tmp_elems=face.getElements()
	
	try:
		master_t=tmp_elems[0].getSection().getThickness()
		master_offs=tmp_elems[0].getSection().getOffset()
		for elem in tmp_elems[1:]:
			tmp_sect=elem.getSection()
			tmp_t=tmp_sect.getThickness()
			tmp_offs=tmp_sect.getOffset()
			if tmp_t != master_t:
				print("Warning: Non uniform thickness detected for face...using thickness of first element found")
				break
			elif tmp_offs != master_offs:
				print("Warning: Non uniform offset detected for face...using offset of first element found")	
				break
		if master_t==0. or master_t=="":
			master_t=t
		if master_offs=="":
			master_offs=offs	
			
	except:
		print("Use defaults")
		master_offs=offs
		master_t=t
	
	print("Thickness is:",master_t," Offset is:", master_offs)
	
	section_1 = apex.catalog.createShellSection( name = SectionName, description = "", thickness = master_t, offset = master_offs)
	_target = apex.EntityCollection()
	_target.append( face )
	apex.attribute.assignShellSection(section = section_1, target = _target )
	
	# Set Custom Attribute to link Section to Face
	# name might have changed with a counter by application so need to retrieve name

	face.addUserAttribute(userAttributeName ="SectionName", stringValue = section_1.getName() )
	
	
	
	
	return



# 
# Start of recorded operations


def main(dict={}):

	startTime = time.process_time()

	_selected = apex.selection.getCurrentSelection()


	Prefix = dict["Prefix"]
	StartId = int(dict["StartId"])
	DefaultThickness = float(dict["DefaultThickness"])
	DefaultOffset = float(dict["DefaultOffset"])
	#apex.disableUndoRedo()
	apex.enableRecoveryFileRecording()
	#apex.disableShowOutput()
	# Code starts here   #
	
	
	if 1==1:
	
		
		if len(_selected) == 0:
			print("No faces selected...")
			return
		else:
 
			in_faces=_selected
			# BeamSolids = apex.EntityCollection()
			# for _tmp in in_solids:
				# #tmp_path_name=tmp_solid.getParent().getName()
				# #print(tmp_path_name)
				# #if tmp_path_name=="Beam_Solids":
				# #	BeamSolids.append(tmp_solid)
				# #
				# # recreate list based on name
				# if _tmp.getName().find("#") > 0:
					# tmp_solid=apex.getSolid( pathName = _tmp.getPath() + "/" + _tmp.getName() )
					# BeamSolids.append(tmp_solid)
				

			print("There are " + str(len(in_faces)) + " faces to process") 
			#CreateSurfaceMesh(mesh_surfs,mesh_size=200,exclude_list=OmitSurfs)
			counter=StartId
			for face in in_faces:
				createAndAssignSection(face,id=counter,prefix="Section_",t=DefaultThickness,offs=DefaultOffset)
				
				
				counter +=1
			


	apex.enableUndoRedo()
	apex.enableRecoveryFileRecording()

	endTime = time.process_time()

	seconds = endTime-startTime
	min, sec = divmod(seconds, 60)

	msg = "Approximate elapsed time: "+"%02d : %02d" % (min, sec)
	print(" ")
	print(msg)

#main()


