#
# 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.
#
# Created 09. March 2021 by Lars Oelgeschlaeger MSC Software

import apex
from statistics import mean


def nodeid(dict=None):
    if dict is None:
        dict = {}

    # creating list with selected nodes:
    nodelist = []

    # get current selection:
    try:
        selected = apex.selection.getCurrentSelection()

        # check if selected entities are nodes (only nodes have attribute 'getCoordinates'):
        for node in selected:
            try:
                coordinates = node.getCoordinates()
            except AttributeError:
                nodelist = 'Other entity than node selected. Select only nodes.'

        # if only nodes are selected, get their IDs:
        if 'Other entity than node selected. Select only nodes.' not in nodelist:
            for node in selected:
                nodeid = node.getId()
                nodelist.append(nodeid)

    # if RuntimeError for current selection occurs, other entities than nodes are selected:
    except RuntimeError:
        nodelist = 'Other entity than node selected. Select only nodes.'

    # if no entity is selected:
    if len(nodelist) == 0:
        nodelist = 'No node selected. Select nodes first.'

    # if only one node is selected:
    if len(nodelist) == 1:
        nodelist = 'Only one node selected. Select more nodes.'

    # if too many nodes selected:
    if 'Only one node selected. Select more nodes.' not in nodelist:
        if 'No node selected. Select nodes first.' not in nodelist:
            if 'Other entity than node selected. Select only nodes.' not in nodelist:
                if len(nodelist) > 40:
                    nodelist = 'Too many nodes selected to fit into text field. Continue without showing node IDs.'

    # output:
    print('Node IDs:', nodelist)

    # create a dictionary with outputdata:  
    name_dict = {"nodeid": nodelist}
    return name_dict


def nodeupdate(dict=None):
    if dict is None:
        dict = {}

    # creating list with selected nodes:
    nodelist = []

    # creating list with coordinates of selected nodes:
    allx = []
    ally = []
    allz = []

    # get current selection:
    try:
        selected = apex.selection.getCurrentSelection()

        # check if selected entities are nodes (only nodes have attribute 'getCoordinates'):
        for node in selected:
            try:
                coordinates = node.getCoordinates()

                # append coordinates of selected nodes to the coordinate lists
                x = node.getX()
                allx.append(x)
                y = node.getY()
                ally.append(y)
                y = node.getZ()
                allz.append(y)

            # check if selected entities are only nodes (only nodes have attribute 'getCoordinates'):
            except AttributeError:
                nodelist = 'Other entity than node selected. Select only nodes.'

        # get the average of the coordinates of the selected nodes (center):
        if len(allx) > 0: 
            xaverage = mean(allx)
            yaverage = mean(ally)
            zaverage = mean(allz)
        else:
            xaverage = ''
            yaverage = ''
            zaverage = ''

        # if only one node is selected:
        if len(allx) == 1:
            nodelist = 'Only one node selected. Select more nodes.'

        # if only nodes are selected, update their coordinates:
        if 'Other entity than node selected. Select only nodes.' not in nodelist:
            if 'Only one node selected. Select more nodes.' not in nodelist:
                for node in selected:
                    nodeid = node.getId()
                    nodelist.append(nodeid)
                    if len(nodelist) > 0:
                        offset = node.updateCoordinates(
                            coordinate=apex.Coordinate(float(xaverage), float(yaverage), float(zaverage)))

    # if RuntimeError for current selection occurs, other entities than nodes are selected:
    except RuntimeError:
        nodelist = 'Other entity than node selected. Select only nodes.'

    # if no entity selected:
    if len(nodelist) == 0:
        nodelist = 'No node selected. Select nodes first.'

    # output:
    print('Node IDs:', nodelist)
    if 'Other entity than node selected. Select only nodes.' not in nodelist:
        if 'No node selected. Select nodes first.' not in nodelist:
            print('Coordinates (x/y/z):', xaverage, '/', yaverage, '/', zaverage)
