#
# 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
# 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 System.Windows.Media as Media
from System.ComponentModel import TypeDescriptor
from System import EventHandler

# Apex references
import Enterprise.UI.Services as SCAServices
import Apex.Infrastructure.CustomToolsHelper
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__) )

# define 3 stages
global stageNames
stageNames = [ "Select Solids", "Select Surfaces", "Select Curves" ]
stageTipColor = [Media.Brushes.Green, Media.Brushes.Red, Media.Brushes.Blue]

# define pick filter for each stage
StagePickTypes = [["BODY",], ["SHEETBODY", "GENERALBODY"], ["WIREBODY",]]

global my_toolProperty
my_toolProperty = apex_sdk.ToolPropertyContainer()

# Set pre-defined properties of ToolPropertyContainer
@apex_sdk.errorhandler
def getUIContent():
    # Set Properties to see the Lightening bolt icon and enable auto-apply behavior
    my_toolProperty.IsAutoAppliedVisible = True
    my_toolProperty.IsAutoApplied = 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"_Tools_CheckBox\resources\_Icon_Robot_48.png")
    my_toolProperty.TitleText = "Stage Button"   

    # Define UI
    my_toolProperty.ToolPropertyContent = getCustomToolPropertyContent()
    my_StageButton.Activate(True)
    my_StageButton.AutoSwitchStage(my_toolProperty.IsAutoApplied)
    TypeDescriptor.GetProperties(my_StageButton)['CurrentStage'].AddValueChanged(my_StageButton, EventHandler(HandleCurrentStageChanged))

    # Handle apply button (green) click event
    my_toolProperty.AppliedCommand = apex_sdk.ActionCommand(System.Action(HandleApplyButton))
    my_toolProperty.ExitCommand = apex_sdk.ActionCommand(System.Action(HandleExitButton))
    TypeDescriptor.GetProperties(my_toolProperty)['IsAutoApplied'].AddValueChanged(my_toolProperty, EventHandler(HandleIsAutoAppliedValueChanged))

    # set default stage
    global currentStage
    currentStage = -1
    
    return my_toolProperty
    
@apex_sdk.errorhandler
def HandleCurrentStageChanged(sender, e):
    apex_sdk.runScriptFunctionDisableOutput(os.path.join(current_file_path, r"selection_stage.py"), "ShowStageContent", {}, CurrentStageChangedCallback)
    
def CurrentStageChangedCallback():
    outdict = apex_sdk.getScriptFunctionReturnData()
    selectedItemsTextBlock.Text = outdict['SELECTIONS']

@apex_sdk.errorhandler
def HandleIsAutoAppliedValueChanged(sender, e):
    my_StageButton.AutoSwitchStage(sender.IsAutoApplied)
    
# Apply button handler (Green check mark)
# This function is called each time the Apply button is clicked
@apex_sdk.errorhandler
def HandleApplyButton():
    dictionary = {}

def HandleResetStages(sender,args):
    dictionary = {}
    my_StageButton.ResetStage()
    
# Define Layout and Components
def getCustomToolPropertyContent():

    # Create a Grid
    my_Grid = WPFControls.Grid()

    # Add 3 Rows and Two Columns
    my_Grid.RowDefinitions.Add( WPFControls.RowDefinition() )
    my_Grid.RowDefinitions.Add( WPFControls.RowDefinition() )
    my_Grid.RowDefinitions.Add( WPFControls.RowDefinition() )
    my_Grid.RowDefinitions.Add( WPFControls.RowDefinition() )
    my_Grid.RowDefinitions.Add( WPFControls.RowDefinition() )
    my_Grid.ColumnDefinitions.Add( WPFControls.ColumnDefinition() )
    my_Grid.ColumnDefinitions.Add( WPFControls.ColumnDefinition() )
     
    # Row 1
    # Create a StageButton
    global my_StageButton
    my_StageButton = Apex.Infrastructure.Controls.StageButton()
    for i in range(3):
        stageItem = Apex.Infrastructure.Controls.StageItem()
        stageItem.Content = stageNames[i]
        stageItem.TipColor = stageTipColor[i]
        types = List[System.String]()
        for type in StagePickTypes[i]:
            types.Add(type)
        stageItem.PickFilterList = types
        stageItem.PickMultiple = True
        my_StageButton.Items.Add(stageItem)
    my_StageButton.CurrentStage = 0

    # Add StageButton to Tool
    WPFControls.Grid.SetRow(my_StageButton, 0)
    WPFControls.Grid.SetColumnSpan(my_StageButton, 2)
    my_Grid.Children.Add(my_StageButton)
    
    # Add the Row 2 controls to the Grid
    resetStagesButton = WPFControls.Button()
    resetStagesButton.Content = "Clear All Stages"
    resetStagesButton.Click+=HandleResetStages
    my_Grid.Children.Add(resetStagesButton)
    WPFControls.Grid.SetRow(resetStagesButton, 1)
    
    # Add the Row 3 controls to the Grid
    global selectedItemsTextBlock
    selectedItemsTextBlock = WPFControls.TextBlock()
    selectedItemsTextBlock.Text = "Selected Items:\n none\n none\n none\n"
    my_Grid.Children.Add(selectedItemsTextBlock)
    WPFControls.Grid.SetRow(selectedItemsTextBlock, 2)
    WPFControls.Grid.SetColumnSpan(selectedItemsTextBlock, 2)
    
    # Return the Grid   
    return my_Grid

@apex_sdk.errorhandler
def HandleExitButton():
    my_StageButton.Activate(False)
    TypeDescriptor.GetProperties(my_StageButton)['CurrentStage'].RemoveValueChanged(my_StageButton, EventHandler(HandleCurrentStageChanged))
    TypeDescriptor.GetProperties(my_toolProperty)['IsAutoApplied'].RemoveValueChanged(my_toolProperty, EventHandler(HandleIsAutoAppliedValueChanged))
