#
# 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
# Data Grid UI Example
# 
import sys
import os
import apex_sdk
import clr

# .NET references
import System
import System.Windows.Controls as WPFControls
import System.Data as WPFData
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"_Tools_Parts DataGrid\resources\_Icon_Robot_48.png")
   my_toolProperty.TitleText = "Parts Data Grid"   

   # Define UI
   my_toolProperty.ToolPropertyContent = getCustomToolPropertyContent()
   
   # Update Grid
   UpdateDataGridData()
   
   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())
  
   # Create a DataGrid
   global myDataGrid
   myDataGrid = WPFControls.DataGrid()      
   
   # Add the DataGrid to the Grid 
   my_Grid.Children.Add(myDataGrid)

   # Return the Grid   
   return my_Grid

# Function to handle the Datagrid "Loaded" event
@apex_sdk.errorhandler
def ResizeColumns(sender,args):
   
   # For this example we'll adjust the column widths
   # We'll make them equal and fit the width of the property panel  
    
   # Get the current width of the DataGrid
   width = myDataGrid.ActualWidth

   # Get the number of columns
   num_cols = myDataGrid.Columns.Count
   
   # Calculate the columns width
   col_width = myDataGrid.ActualWidth/myDataGrid.Columns.Count
    
   # Set the width of each columns
   for column in myDataGrid.Columns:
       column.Width = WPFControls.DataGridLength(col_width)   
    

# Apply button handler (Green check mark)
# This function is called each time the Apply button is clicked
@apex_sdk.errorhandler
def UpdateDataGridData():
    
   # Call the Apex API script using apex_sdk.runScriptFunction()
   # argument 1 = the fully qualified path name of your API script
   # argument 2 is the name of the function in your API script that will receive the Dictionary
   # argument 3 is the Dictionary containing the UI data
   apex_sdk.runScriptFunction(os.path.join(current_file_path, r"parts_data_grid.py"),
                              "prepare_data_grid",
                              callback=UpdateDataGridView)


#This function receives data from the Script API function and updates the Tool UI 
@apex_sdk.errorhandler
def UpdateDataGridView():

   # Retrieve grid results
   grid = apex_sdk.getScriptFunctionReturnData()

   # Create parts table
   data_table = WPFData.DataTable("Part Contents")
   data_table.Columns.Add("Part")
   data_table.Columns.Add("Nodes")
   data_table.Columns.Add("Elements")
   
   # Add data to the table for each part
   parts = grid['parts']
   for part in parts:      
      data_table.Rows.Add(part['part_name'], part['nodes_count'], part['elements_count'])
   
   # Set the IetmsSource for the data grid to the DataTable 
   myDataGrid.ItemsSource = data_table.DefaultView 
   
   # Position the DataGrid in the first row, column of the Grid
   WPFControls.Grid.SetRow(myDataGrid, 0)
   WPFControls.Grid.SetColumn(myDataGrid, 0)
