#
# Copyright © 2021 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
# Mesh Selected Bodies 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
from Microsoft.Win32 import SaveFileDialog

# import pydevd_pycharm
# pydevd_pycharm.settrace('localhost', port=54280, stdoutToServer=True, stderrToServer=True)

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


# Set pre-defined properties of ToolPropertyContainer
@apex_sdk.errorhandler
def getUIContent():

   global my_toolProperty
   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"Icons\display_field_as_fringe.png")
   my_toolProperty.TitleText = "Display Spatial Load"

   # Define UI
   my_toolProperty.ToolPropertyContent = getCustomToolPropertyContent()

   # Handle apply button (green) click event
   my_toolProperty.AppliedCommand = apex_sdk.ActionCommand(System.Action(HandleApplyButton))

   my_toolProperty.ShowPickChoice = True
   my_toolProperty.PickFilterList = setPickFilterList()

   return my_toolProperty


@apex_sdk.errorhandler
def setPickFilterList():
   # Create an empty List of strings
   pickChoices = System.Collections.Generic.List[System.String]()

   # Exclusive picking and visibility picking
   pickChoices.Add(apex_sdk.PickFilterTypes.ExclusivePicking)
   pickChoices.Add(apex_sdk.PickFilterTypes.VisibilityPicking)

   pickChoices.Add(apex_sdk.PickFilterTypes.Pressure)
   pickChoices.Add(apex_sdk.PickFilterTypes.LoadTemperature)

   # Return the pick filter list
   return pickChoices


# Define Layout and Components
@apex_sdk.errorhandler
def getCustomToolPropertyContent():

   # Top level stack panel
   top_panel = WPFControls.StackPanel()


   render_opt_stack_panel = WPFControls.StackPanel()
   top_panel.Children.Add(render_opt_stack_panel)

   # # Create a label for the first radio button array
   model_options_text_box = WPFControls.TextBlock()
   model_options_text_box.Text = "Display Scope"
   render_opt_stack_panel.Children.Add(model_options_text_box)
   #
   # Create a vertical array of three radio buttons
   # Create a WrapPanel
   hWrapPanel = WPFControls.WrapPanel()

   global model_options_radio_buttons
   model_options_radio_buttons = []

   # Create a  radio button
   # Add it to the list and to the WrapPanel
   model_options_radio_buttons.append(WPFControls.RadioButton())
   model_options_radio_buttons[0].Click  += HandleTransferOptions
   model_options_radio_buttons[0].Content = "All"

   model_options_radio_buttons[0].IsChecked = System.Nullable[System.Boolean](True)
   hWrapPanel.Children.Add(model_options_radio_buttons[0])

   # Create a  radio button and add to the WrapPanel
   model_options_radio_buttons.append(WPFControls.RadioButton())
   model_options_radio_buttons[1].Content = "Region"
   hWrapPanel.Children.Add(model_options_radio_buttons[1])

   render_opt_stack_panel.Children.Add(hWrapPanel)

   top_panel.Children.Add(WPFControls.Separator())

   global savecheckbox
   savecheckbox = WPFControls.CheckBox()
   savecheckbox.Content = 'Save Field in VTK File'
   savecheckbox.Margin = System.Windows.Thickness(5.)
   savecheckbox.Checked   += saveToggleCB
   savecheckbox.Unchecked += saveToggleCB

   top_panel.Children.Add(savecheckbox)

   global save_stack_panel
   save_stack_panel = WPFControls.StackPanel()
   save_stack_panel.Visibility   = System.Windows.Visibility.Collapsed
   save_stack_panel.Orientation = WPFControls.Orientation.Horizontal

   selectBtn = WPFControls.Button()
   selectBtn.Content = "VTK File ..."
   selectBtn.Click += HandleVTKButton

   # Create an empty input TextBox to display the file name
   # Row 0 = Parsolid Base plate file
   global VTKfileNameTextBox
   VTKfileNameTextBox = WPFControls.TextBox()
   VTKfileNameTextBox.Text=''
   VTKfileNameTextBox.Width = 150

   save_stack_panel.Children.Add(selectBtn)
   save_stack_panel.Children.Add(VTKfileNameTextBox)
   
   top_panel.Children.Add(save_stack_panel)

   return top_panel

@apex_sdk.errorhandler
def saveToggleCB(sender,event):
    global save_stack_panel 
    if sender.IsChecked:
        save_stack_panel.Visibility   = System.Windows.Visibility.Visible
        if VTKfileNameTextBox.Text == '':
            HandleVTKButton(None,None)
    else:
        save_stack_panel.Visibility   = System.Windows.Visibility.Collapsed
        

@apex_sdk.errorhandler  
def HandleVTKButton(sender,event):

   # Create a File open dialog
    dialog = SaveFileDialog ()
   # Configure for single file selection
    dialog.Multiselect = False

   # Set up the file types you want to support
    dialog.Filter = "Vtp Files|*.vtp|All Files|*.*"
   # Display the dialog
   # If it returns anything
   #   1) Get the file name
   #   2) Display it on the text box
    if dialog.ShowDialog():
      vtkFile = dialog.FileName
      VTKfileNameTextBox.Text = vtkFile
      VTKfileNameTextBox.Focus()
      VTKfileNameTextBox.Select(len(VTKfileNameTextBox.Text), 0)

   
# Apply button handler (Green check mark)
# This function is called each time the Apply button is clicked
@apex_sdk.errorhandler
def HandleApplyButton():

   global VTKfileNameTextBox
   # Create a Dictionary to store the user defined tool data  
   dictionary = {}

   model_display_scope = "All"
   if model_options_radio_buttons[0].IsChecked:
      model_display_scope = "All"
   elif model_options_radio_buttons[1].IsChecked:
      model_display_scope = "Region"

   if savecheckbox.IsChecked:
      save_vtk_file=VTKfileNameTextBox.Text
   else:
      save_vtk_file=''

   # Populate the Dictionary with the user defined tool data you need
   # dictionary["visualization_target_type"]  = visualization_target_type
   dictionary["model_display_scope"]     = model_display_scope
   dictionary["save_vtk_file"]   =  save_vtk_file


   # Call you Apex API script using the sunrScriptFunction() method
   # 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, "display_spatial_load.py"),
                              "display_apex_entities_in_vtk_window",
                              dictionary)


