#
# 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.
#
# MSC Apex - User Defined Tools using Python Scripts
# Assembly Part Tree View UI Example
# 
import sys
import os
import apex_sdk
import clr

# .NET references
import System
import System.Windows.Controls as WPFControls
from Microsoft.Win32 import OpenFileDialog

# Define current file path of example
current_file_path = os.path.dirname(os.path.realpath(__file__))


# Set pre-defined properties of ToolPropertyContainer
def getUIContent():
   my_toolProperty = apex_sdk.ToolPropertyContainer()
   
   # Provide an icon and a name for the tool property panel
   my_toolProperty.TitleImageUriString = os.path.join(os.path.dirname(current_file_path), r"res\Robot.png")
   my_toolProperty.TitleText = "Assembly Part Tree View"   

   # Define UI
   my_toolProperty.ToolPropertyContent = getCustomToolPropertyContent()

   # Update Tree
   UpdateTreeModelData()

   return my_toolProperty


# Define Layout and Components
def getCustomToolPropertyContent():

   # Create a Grid
   my_Grid = WPFControls.Grid()
   # Add 1 Row and One Column
   my_Grid.RowDefinitions.Add(WPFControls.RowDefinition())
   my_Grid.ColumnDefinitions.Add(WPFControls.ColumnDefinition())
   my_Grid.Height = 500
     
   # Create global tree view object to be used later for updating
   global treeView
   treeView = WPFControls.TreeView()
   my_Grid.Children.Add(treeView)

   # Position the WrapPanel in the first row, column of the Grid
   WPFControls.Grid.SetRow(treeView, 0)
   WPFControls.Grid.SetColumn(treeView, 0)

   # Return the Grid   
   return my_Grid


# Apply button handler (Green check mark)
# This function is called each time the Apply button is clicked
@apex_sdk.errorhandler
def UpdateTreeModelData():
      
   # Call you Apex API script using the runScriptFunction() method
   # argument 1 = the fully qualified path name of your API script
   # argument 2 = the name of the function in your API script that will receive the Dictionary
   # argument 3 = the name of the UI Function that handle data returned by the API script function
   apex_sdk.runScriptFunction(os.path.join(current_file_path, r"assembly_part_tree_view.py"),
                              "prepare_assembly_part_tree_view",
                              callback=UpdateTreeView)


#This function receives data from the Script API function and updates the Tool UI 
@apex_sdk.errorhandler
def UpdateTreeView():
   # Retrieve tree results
   model_tree = apex_sdk.getScriptFunctionReturnData()

   # Create tree root node 'Assemblies'
   root = WPFControls.TreeViewItem()
   treeView.Items.Add(root)
   root.Header = "Model"
   root.IsExpanded = True

   if "name" in model_tree:
      addAssemblyItem(root, model_tree)



def addAssemblyItem(root, assembly_dict):
   assemblyItem = WPFControls.TreeViewItem()
   assemblyItem.IsExpanded = True
   root.Items.Add(assemblyItem)
   # Add assembly total node and element counts
   assemblyItem.Header = assembly_dict["name"] + \
                         " (" + str(assembly_dict["node_count"]) + \
                         " " + str(assembly_dict["element_count"]) + ")"
   if "sub_assembies" in assembly_dict:
      for sub_assembly_dict in assembly_dict["sub_assembies"]:
         addAssemblyItem(assemblyItem, sub_assembly_dict)

   if "parts" in assembly_dict:
      for part_dict in assembly_dict["parts"]:
         addPartItem(assemblyItem, part_dict)

   return assemblyItem


def addPartItem(root, part_dict):
   partItem = WPFControls.TreeViewItem()
   partItem.IsExpanded = True
   root.Items.Add(partItem)
   # Add assembly total node and element counts
   partItem.Header = part_dict["name"] + \
                         " (" + str(part_dict["node_count"]) + \
                         " " + str(part_dict["element_count"]) + ")"
   return partItem