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

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

import Apex.Infrastructure
clr.AddReference("System.Collections")
from System.Collections.Generic import List

# 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()
   # Automation Id is needed for internal testing ONLY
   my_toolProperty.SetValue(AutomationProperties.AutomationIdProperty, "AID_USER_TOOL_PROPERTY_MODE");
   my_toolProperty.applyMMB = True;
   
   # 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_48.png")
   my_toolProperty.TitleText = "Stage Button"   

   # Define UI
   my_toolProperty.ToolPropertyContent = getCustomToolPropertyContent()
   
   # Handle apply button (green) click event
   my_toolProperty.AppliedCommand = apex_sdk.ActionCommand(System.Action(HandleApplyButton))
   
   apex_sdk.registerGestureHandler( HandleGesture )
   
   return my_toolProperty

def HandleGesture( ToolGestureEventData, args ):
    # ignore Mouse, Continue, and KeyPress Gestures...
	
	# Here is where the selection state logic is implemented. 
	# In this exammple, when mouse event is detected, it's stage 0
	# When keyboard event is detected, it's stage 1
	
    if "Mouse" in ToolGestureEventData.ges.gestureName:
        stages[0].IsActive = True
        return
    if "Continue" in ToolGestureEventData.ges.gestureName:
        return
    if "KeyPress" in ToolGestureEventData.ges.gestureName:
        stages[1].IsActive = True
        return
    # get count of current selection list from GestureEventStruct (ges)
    count = 0
    if (ToolGestureEventData.ges.currentSelectionList != None ):
        count = ToolGestureEventData.ges.currentSelectionList.count()
    # print a message to console...
    print('check_box_ui.py HandleGesture: gestureName = ', ToolGestureEventData.ges.gestureName, 'Selected Item Count = ', count )

# 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.RowDefinitions.Add(WPFControls.RowDefinition())
   my_Grid.ColumnDefinitions.Add(WPFControls.ColumnDefinition())
     
   # Create a vertical array of three check boxes using WrapPanel
   myWrapPanel = WPFControls.WrapPanel()
   myWrapPanel.Orientation=WPFControls.Orientation.Vertical
   
   # Create a List to hold the check boxes
   # Use this later to make it easier to find which button is checked 
   global check_boxes
   check_boxes = [] 

   # Create the first check box
   # Add it to the list and to the WrapPanel
   check_boxes.append(WPFControls.CheckBox())
   check_boxes[0].Content = "Option 1"
   # Check this checkbox
   # Note the horrible notation required to define a Nullable Boolean True
   check_boxes[0].IsChecked = System.Nullable[System.Boolean](True)
   myWrapPanel.Children.Add(check_boxes[0])
 
   # Create a second radio button and add to the WrapPanel
   check_boxes.append(WPFControls.CheckBox())
   check_boxes[1].Content = "Option 2"
   myWrapPanel.Children.Add(check_boxes[1])
   
   # Create a third radio button and add to the WrapPanel
   check_boxes.append(WPFControls.CheckBox())
   check_boxes[2].Content = "Option 3"
   myWrapPanel.Children.Add(check_boxes[2])

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

   # Add the WrapPanel to the Grid 
   my_Grid.Children.Add(myWrapPanel)

   # Create a StageButton
   my_StageButton = Apex.Infrastructure.Controls.StageButton()
   # Define the stages for the StageButton
   global stages
   stages = List[Apex.Infrastructure.ViewModels.StageViewModel]()
   stages.Add(Apex.Infrastructure.ViewModels.StageViewModel())
   stages[0].Content = "Mouse"
   stages.Add(Apex.Infrastructure.ViewModels.StageViewModel())
   stages[1].Content = "KeyPress"
   my_StageButton.Stages = stages

   # Add StageButton to Tool
   WPFControls.Grid.SetRow(my_StageButton, 1)
   my_Grid.Children.Add(my_StageButton)

   # 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 HandleApplyButton():
   
   # Create a Dictionary to store the user defined tool data  
   dictionary = {}
 
   # Find the checked button in radio_button_array_1
   # And store it in the dictionary 
   # Note that this is somewhat safe since only one radio button can be checked    
   dictionary["check_box_1"] = check_boxes[0].IsChecked
   dictionary["check_box_2"] = check_boxes[1].IsChecked
   dictionary["check_box_3"] = check_boxes[2].IsChecked
   
   # Call the Apex API script using apex_sdk.runScriptFunction()
   # 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 Dictionary containing the UI data
   apex_sdk.runScriptFunction(os.path.join(current_file_path, r"stage_button.py"), "read_check_boxes", dictionary)
