# 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.
#

# Author: Larry Pearce
# Revised by: Larry Pearce
# Revision History
# Date         Change                                 By
# 2020-10-13   Original code                          Larry Pearce


import apex


def flexibleLinkProps(dia, matl):
    # Input:   variable        datatype         description
    #          dia             float            fastener diameter
    #          matl            object           fastener material
    # Output:  variable        datatype         description
    #          connProps       connector property object
    #
    # Creates a flexible link connection property
    
    connProps = apex.attribute.createConnectorProperties(
          stiffness               = 0.0,
          damping                 = 0.0,
          translationalStiffnessX = 0.0,
          translationalStiffnessY = 0.0,
          translationalStiffnessZ = 0.0,
          rotationalStiffnessX    = 0.0,
          rotationalStiffnessY    = 0.0,
          rotationalStiffnessZ    = 0.0,
          translationalDampingX   = 0.0,
          translationalDampingY   = 0.0,
          translationalDampingZ   = 0.0,
          rotationalDampingX      = 0.0,
          rotationalDampingY      = 0.0,
          rotationalDampingZ      = 0.0,
          diameter                = dia,
          linkMaterial            = matl)
    return connProps


def main(dict={}):
    myModel = apex.currentModel()

    # Get the data entered on the form from the dictionary
    updateMatl = dict["updateMaterial"]
    updateDia  = dict["updateDiameter"]

    matlName   = dict["material"]
    dia        = dict["diameter"]

    # If the update material and update diameter toggles are not selected, then no connectors will be updated
    if updateMatl == "False" and updateDia == "False":
        print("No connectors will be updated!")
        return

    # Check to see that connectors were selected
    _selected = apex.selection.getCurrentSelection()
    print("Selected connectors: " + str(_selected.len()))
    if _selected.len() == 0 and "isTest" in dict.keys():
        assys = myModel.getAssemblies()
        if assys.len() == 0:
            print("No Assemblies found!")
            return
        for assy in assys:
            conns = apex.attribute.getConnectors([{"path":assy.getPath()}])
            _selected.extend(conns)
        print("Assembly connectors: " + str(_selected.len()))
    if _selected.len() == 0:
        print("No connectors selected!")
        return

    # This is some code to get all connectors if none were selected.  I am omitting this for now
    # if _selected.len() == 0:
    #    assys = myModel.getAssemblies()
    #    if assys.len() == 0:
    #        print("No Assemblies found!")
    #        return
    #    for assy in assys:
    #        conns = apex.attribute.getConnectors([{"path":assy.getPath()}])
    #        _selected.extend(conns)
    #    print("Assembly connectors: " + str(_selected.len()))
    # if _selected.len() == 0:
    #    print("No connectors selected nor found in an Assembly!")
    #    return

    # If the user selected to update the material, then get the object associated to the selected material name
    if updateMatl == "True":
        fastenerMatl = None
        matls = apex.catalog.getMaterials([{"path":myModel.getName()+"/Materials"}])
        for matl in matls:
            if matl.getName() == matlName:
                fastenerMatl = matl
                break
        if fastenerMatl == None:
            print("Unknown material?")
            return

    # If the user selected to update the diameter, then check to make sure the diameter is not zero
    if updateDia == "True":
        dia = float(dia)
        if dia <= 0.0:
            print("Entered diameter <= 0.0!")
            return

    numConnectorsEdited  = 0
    numNotFlexible       = 0
    for conn in _selected:
        # All connector types can be selected.  Only process the flexible links
        if conn.getConnectorType() != apex.attribute.ConnectorType.FlexibleLink:
            numNotFlexible += 1
            continue

        # Get default data if a toggle is not selcged
        if updateMatl != "True": fastenerMatl = conn.getLinkMaterial()
        if updateDia  != "True": dia          = conn.getDiameter()

        # Update the connector property
        connProps = flexibleLinkProps(dia, fastenerMatl)

        # Update the connector with the new connector property
        conn.update(connectorProperties = connProps)

        numConnectorsEdited += 1

    print("Connectors updated: "+str(numConnectorsEdited))

    print(str(numNotFlexible) + " of the selected connectors were not Flexible connectors")



