#
# 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
# File Dialog UI Example
# 
import sys
import os
import time
import apex_sdk
import clr

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

# For selection stages......
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__))
res_path = os.path.join(os.path.dirname(current_file_path), 'res')

need_units = True
tselect = False
times = time.time()


# Set pre-defined properties of ToolPropertyContainer
def getUIContent():
    global map_field_tool_property_panel
    map_field_tool_property_panel = apex_sdk.ToolPropertyContainer()

    # Provide an icon and a name for the tool property panel
    map_field_tool_property_panel.TitleImageUriString = os.path.join(os.path.dirname(current_file_path),
                                                                     r"res\map_field.png")
    map_field_tool_property_panel.TitleText = "Map Load Field"

    # Define UI
    map_field_tool_property_panel.ToolPropertyContent = getCustomToolPropertyContent()

    apex_sdk.registerGestureHandler(HandleGesture)

    # handle exit button (red) click event
    map_field_tool_property_panel.ExitCommand = apex_sdk.ActionCommand(System.Action(HandleExitButton))

    # reuse previous content
    dict = {'need_units' : need_units}
    apex_sdk.runScriptFunction(os.path.join(current_file_path, "display_map_field.py"),
                               "get_current_info",
                               dict,
                               callback=CheckUserInput)

    return map_field_tool_property_panel


# Define Layout and Components
def getCustomToolPropertyContent():
    # Top level stack panel that contains all of the UI controls
    primary_panel = WPFControls.StackPanel()
    primary_panel.Orientation = WPFControls.Orientation.Vertical

    #######   Source Selection   ########

    # Stack panel for the UI controls to choose the source field
    global source_select_stack_panel
    source_select_stack_panel = WPFControls.StackPanel()
    source_select_stack_panel.Orientation = WPFControls.Orientation.Vertical
    primary_panel.Children.Add(source_select_stack_panel)

    #######   Source Selection  - Label  ########
    source_select_text_box = WPFControls.TextBlock()
    source_select_text_box.Text = "Define source field"
    source_select_stack_panel.Children.Add(source_select_text_box)

    #######   Source Selection  - Radio buttons  ########
    ####### Not currently used - add this back when we support mapping from Apex fields
    # Radio buttons to choose external or internal source field
    # Create a WrapPanel for the source type radio buttons
    source_type_radio_button_wrap_panel = WPFControls.WrapPanel()
    source_type_radio_button_wrap_panel.Orientation = WPFControls.Orientation.Horizontal

    ######   External source selection from file #######
    external_source_file_selection_wrap_panel = WPFControls.WrapPanel()
    external_source_file_selection_wrap_panel.Orientation = WPFControls.Orientation.Horizontal
    source_select_stack_panel.Children.Add(external_source_file_selection_wrap_panel)

    #######   Source Selection  - Display Source Name ########
    global source_name_textbox
    source_name_textbox = WPFControls.TextBox()
    source_name_textbox.Content = ""
    source_name_textbox.Width = 325
    # source_name_textbox.TextChanged += HandleSourceChange
    external_source_file_selection_wrap_panel.Children.Add(source_name_textbox)


    #######   Source Selection  - File chooser  ########
    global external_source_selection_btn
    external_source_selection_btn = WPFControls.Button()
    external_source_selection_btn.Click += ChooseExternalFile
    external_source_selection_btn.Content = "Browse..."
    # image_uri = System.Uri(os.path.join(res_path, r"open_file.png"))
    # file_open_image = WPFControls.Image()
    # file_open_image.Source = System.Windows.Media.Imaging.BitmapImage(image_uri)
    # external_source_selection_btn.Content = file_open_image
    external_source_file_selection_wrap_panel.Children.Add(external_source_selection_btn)

    ######   External source selection from file #######

    global source_units_display_wrap_panel
    source_units_display_wrap_panel = WPFControls.WrapPanel()
    source_units_display_wrap_panel.Orientation = WPFControls.Orientation.Horizontal
    source_select_stack_panel.Children.Add(source_units_display_wrap_panel)

    #######   Source Selection  - UNist combo  ########
    global units_combo
    units_combo = WPFControls.ComboBox()
    units_combo.IsEnabled = False
    source_units_display_wrap_panel.Children.Add(units_combo)

    #######   Source Selection  - UNist combo  ########
    global field_type_combo
    field_type_combo = WPFControls.ComboBox()
    field_type_combo.IsEnabled = False
    source_units_display_wrap_panel.Children.Add(field_type_combo)


    #######   Source Selection  - Display Source  ########
    global display_source_btn
    display_source_btn = WPFControls.Button()
    display_source_btn.Click += DisplayField
    display_source_btn.Content = "Display Source Field"
    display_source_btn.Width = 150
    display_source_btn.IsEnabled = False
    source_units_display_wrap_panel.Children.Add(display_source_btn)

    #######   Target Selection    ########
    #######   Target Selection Selection  - Stack Panel  ########
    global target_select_stack_panel
    target_select_stack_panel = WPFControls.StackPanel()
    target_select_stack_panel.Visibility = System.Windows.Visibility.Collapsed
    primary_panel.Children.Add(target_select_stack_panel)

    target_select_stack_panel.Children.Add(WPFControls.Separator())

    #######   Target Selection Selection  - Label  ########
    target_select_text_box = WPFControls.TextBlock()
    target_select_text_box.Text = "Define Target"
    target_select_stack_panel.Children.Add(target_select_text_box)

    # DB4L8R - Add support for selection stage button when it is working
    # For now, just use a regular button
    global target_selection_btn
    target_selection_btn = WPFControls.Button()
    target_selection_btn.Click += TargetEntitiesFocus
    target_selection_btn.Content = "Select target"
    target_select_stack_panel.Children.Add(target_selection_btn)

    #######   Target Selection  - Display Target Name ########
    # This will move onto the Selection Stage button in the future
    global target_entities_textbox
    target_entities_textbox = WPFControls.TextBox()

    target_entities_textbox.Content = ""
    target_entities_textbox.TextChanged += HandleTargetChange

    target_select_stack_panel.Children.Add(target_entities_textbox)

    global mapping_stack_panel
    mapping_stack_panel = WPFControls.StackPanel()
    primary_panel.Children.Add(mapping_stack_panel)
    mapping_stack_panel.Visibility = System.Windows.Visibility.Collapsed

    mapping_stack_panel.Children.Add(WPFControls.Separator())

    #######   Source Selection  - Label  ########
    mapping_text_box = WPFControls.TextBlock()
    mapping_text_box.Text = "Define Mapping"

    mapping_stack_panel.Children.Add(mapping_text_box)

    tol_panel=WPFControls.StackPanel()
    tol_panel.Orientation = WPFControls.Orientation.Horizontal

    global TolBlock
    TolBlock = WPFControls.CheckBox()
    TolBlock.Content = "Tolerance"
    TolBlock.Click += HandleTolCheck
    mapping_stack_panel.Children.Add(tol_panel)
    tol_panel.Children.Add(TolBlock)

    global TolTextBox
    TolTextBox = WPFControls.TextBox()
    TolTextBox.Text = ".009"
    TolTextBox.Height = 20
    TolTextBox.Width = 50
    TolTextBox.Visibility = System.Windows.Visibility.Collapsed
    tol_panel.Children.Add(TolTextBox)


    #######   Source Selection  - Radio buttons  ########
    # Radio buttons to choose external or internal source field
    # Create a WrapPanel for the source type radio buttons
    mapping_algorithm_radio_buttons_wrap_panel = WPFControls.WrapPanel()
    mapping_algorithm_radio_buttons_wrap_panel.Orientation = WPFControls.Orientation.Horizontal

    # Create a List to hold the radio buttons in the first array
    # We'll use this later to make it easier to find which button is checked
    global mapping_algorithm_radio_buttons
    mapping_algorithm_radio_buttons = []

    global current_mapping_algorithm
    current_mapping_algorithm = None

    # Create a radio button
    # Add it to the list and to the WrapPanel
    mapping_algorithm_radio_buttons.append(WPFControls.RadioButton())
    mapping_algorithm_radio_buttons[0].Click += HandleMappingOptions
    mapping_algorithm_radio_buttons[0].Content = "Point cloud or mesh"
    current_mapping_algorithm = "Point cloud or mesh"

    # Set the first radio button to be checked
    # Note the horrible notation required to define a Nullable Boolean True
    mapping_algorithm_radio_buttons[0].IsChecked = System.Nullable[System.Boolean](True)
    mapping_algorithm_radio_buttons_wrap_panel.Children.Add(mapping_algorithm_radio_buttons[0])

    # Create a radio button
    # Add it to the list and to the WrapPanel
    mapping_algorithm_radio_buttons.append(WPFControls.RadioButton())
    mapping_algorithm_radio_buttons[1].Click += HandleMappingOptions
    mapping_algorithm_radio_buttons[1].Content = "Mesh only"
    # Set the first radio button to be checked
    # Note the horrible notation required to define a Nullable Boolean True
    mapping_algorithm_radio_buttons[1].IsChecked = System.Nullable[System.Boolean](False)
    mapping_algorithm_radio_buttons_wrap_panel.Children.Add(mapping_algorithm_radio_buttons[1])



    # Create a radio button
    # Add it to the list and to the WrapPanel
    mapping_algorithm_radio_buttons.append(WPFControls.RadioButton())
    mapping_algorithm_radio_buttons[2].Click += HandleMappingOptions
    mapping_algorithm_radio_buttons[2].Content = "Coarse to fine"
    # Set the first radio button to be checked
    # Note the horrible notation required to define a Nullable Boolean True
    mapping_algorithm_radio_buttons[2].IsChecked = System.Nullable[System.Boolean](False)
    mapping_algorithm_radio_buttons_wrap_panel.Children.Add(mapping_algorithm_radio_buttons[2])

    mapping_stack_panel.Children.Add(mapping_algorithm_radio_buttons_wrap_panel)

    mapping_algorithm_radio_buttons[1].IsEnabled = False
    mapping_algorithm_radio_buttons[2].IsEnabled = False

    #######   Map Source  ########
    global map_source_to_target_btn
    map_source_to_target_btn = WPFControls.Button()
    map_source_to_target_btn.Click += HandleMapSourceToTarget
    map_source_to_target_btn.Content = "Preview mapped field"
    map_source_to_target_btn.IsEnabled = False
    mapping_stack_panel.Children.Add(map_source_to_target_btn)

    ###   Create the Load #######

    global load_panel
    load_panel = WPFControls.StackPanel()
    # load_panel.Visibility = System.Windows.Visibility.Hidden
    load_panel.IsEnabled = False
    load_name_panel = WPFControls.StackPanel()
    load_name_panel.Orientation = WPFControls.Orientation.Horizontal
    load_panel.Children.Add(load_name_panel)

    # Create a label for the first radio button array
    TextBlock = WPFControls.TextBlock()
    TextBlock.Text = "Name  "
    load_name_panel.Children.Add(TextBlock)

    global NameTextBox
    NameTextBox = WPFControls.TextBox()
    NameTextBox.Text = ""
    NameTextBox.Height = 20
    NameTextBox.Width = 100
    load_name_panel.Children.Add(NameTextBox)

    # Create a label for the first radio button array

    global outer_checkbox
    outer_checkbox = WPFControls.CheckBox()
    outer_checkbox.Content = 'Outer Nodes Only'
    outer_checkbox.Margin = System.Windows.Thickness(5.)
    outer_checkbox.Visibility = System.Windows.Visibility.Collapsed
    load_name_panel.Children.Add(outer_checkbox)

    #######   Map Source  ########
    global create_source_to_target_btn
    create_source_to_target_btn = WPFControls.Button()
    create_source_to_target_btn.Click += HandleMapSourceToTarget
    create_source_to_target_btn.Content = "Create Load"
    # create_source_to_target_btn.IsEnabled = False
    load_panel.Children.Add(create_source_to_target_btn)

    mapping_stack_panel.Children.Add(load_panel)
    # primary_panel.Children.Add(load_panel)

    return primary_panel



@apex_sdk.errorhandler
def update_units_combo(units_info):
    for unit in units_info:
        item = WPFControls.ComboBoxItem()
        item.Content = unit
        units_combo.Items.Add(item)
    units_combo.SelectedIndex = "0"

@apex_sdk.errorhandler
def HandleExitButton():
    global tselect
    tselect = False
    apex_sdk.runScriptFunction(os.path.join(current_file_path, "display_map_field.py"),
                               "reset_current_info")




@apex_sdk.errorhandler
def CheckUserInput():
    output = apex_sdk.getScriptFunctionReturnData()
    if output == None:
        return

    if output.get('units', None) is not None:
        update_units_combo(output['units'])

    NameTextBox.Text = ""
    if output.get('method', None) == 'preview_file':
        preview_data = output.get('preview_data', None)
        if preview_data is not None:
            locs = preview_data.get('locs', None)
            pres = preview_data.get('pres', None)
            temp = preview_data.get('temp', None)
            if locs is not None and locs != False:
                field_type_combo.Items.Clear()
                if pres is not None and pres != False:
                    scalar_field_pressure_item = WPFControls.ComboBoxItem()
                    scalar_field_pressure_item.Content = 'Pressure'
                    field_type_combo.Items.Add(scalar_field_pressure_item)
                if temp is not None and temp != False:
                    scalar_field_temp_item = WPFControls.ComboBoxItem()
                    scalar_field_temp_item.Content = 'Temperature'
                    field_type_combo.Items.Add(scalar_field_temp_item)

                if temp is None and pres is None:
                    source_name_textbox.Text = 'No Pressure or Temperature found'
                else:
                    field_type_combo.SelectedIndex = "0"
                    filename = output.get('filename', None)
                    if filename is not None:
                        source_name_textbox.Text = str(filename)
                    else:
                        source_name_textbox.Text = 'Problem reading file'

                    display_source_btn.IsEnabled = True
                    field_type_combo.IsEnabled = True
                    units_combo.IsEnabled = True

                    target_entities_textbox.Text = ""
                    target_select_stack_panel.Visibility = System.Windows.Visibility.Visible
                    mapping_stack_panel.Visibility = System.Windows.Visibility.Collapsed

                    # if output['scalar_fields']['temp']:
                    #     NameTextBox.Text = "Temperature"
                    # #     outer_checkbox.Visibility = System.Windows.Visibility.Visible
                    # # else:
                    # #     outer_checkbox.Visibility = System.Windows.Visibility.Collapsed
                    # if output['scalar_fields']['pres']:
                    #     NameTextBox.Text = "Pressure"
                    # #     TolBlock.Visibility = System.Windows.Visibility.Visible
                    # # else:
                    # #     TolBlock.Visibility = System.Windows.Visibility.Collapsed
            #
            #
            else:
                print('Bad header')
                header = preview_data.get('headers', None)
                if header is not None:
                    source_name_textbox.Text = 'Bad Header! ' + str(header)




        #
        #
        # if output['file_extension'] == '.csv':
        #     if 'scalar_fields' in output.keys():
        #         if not output['scalar_fields']['loc']:
        #             source_name_textbox.Text = 'Wrong Header! ' + str(output['scalar_fields']['headers'])
        #             return
        #         else:
        #             print('Processing scalar fields')
        #             for scalar_field in output['scalar_fields']:
        #                 print(scalar_field)
        #                 scalar_field_item = WPFControls.ComboBoxItem()
        #                 scalar_field_item.Content = scalar_field
        #                 field_type_combo.Items.Add(scalar_field_item)
        #             field_type_combo.SelectedIndex = "0"
        # elif output['file_extension'] == '.xml':
        #     if output.get('scalar_fields', None) is not None:
        #         for scalar_field, scalar_field_present in output['scalar_fields'].items():
        #             print(scalar_field, scalar_field_present)
        #             if scalar_field_present == True:
        #                 print("Adding ", scalar_field, 'to field_type_combo')
        #                 scalar_field_item = WPFControls.ComboBoxItem()
        #                 scalar_field_item.Content = scalar_field
        #                 field_type_combo.Items.Add(scalar_field_item)
        #         field_type_combo.SelectedIndex = "0"
        #
        # if output['filename'] != '':
        #     source_name_textbox.Text = output['filename']
        #     source_name_textbox.Focus()
        #     source_name_textbox.Select(len(source_name_textbox.Text), 0)



    if output['method'] == 'get_current_info':
        if output['source_filename'] != '':
            source_name_textbox.Text = output['source_filename']
            update_units_combo.IsEnabled = True
            source_units_display_wrap_panel.Visibility = System.Windows.Visibility.Visible
            display_source_btn.IsEnabled = True
            target_select_stack_panel.Visibility = System.Windows.Visibility.Visible
            if output['tol'] != '':
                TolBox.IsChecked=True
                TolTextBox.Text = output['tol']
            if output['ftype'] != '':
                NameTextBox.Text = output['ftype']

        target_entities_textbox.Text = output['target']

    # if 'header' in output.keys():
    #    window = System.Windows.Window()
    #    window.Title="Check the file ..."
    #    # window.Content = getCustomToolPropertyContent1)
    #    window.MinWidth = 500
    #    window.TopMost= True
    #    window.SetResourceReference(System.Windows.Window.StyleProperty, "DefaultUserPopupWindowStyle")
    #    window.ShowDialog()

@apex_sdk.errorhandler
def setPickFilterListFieldSource():
    # 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.Temperature)

    # Return the pick filter list
    return pickChoices

@apex_sdk.errorhandler
def setPickFilterListMeshTarget():
    # 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.Solid)
    # pickChoices.Add(apex_sdk.PickFilterTypes.Surface)
    pickChoices.Add(apex_sdk.PickFilterTypes.SolidMesh)
    pickChoices.Add(apex_sdk.PickFilterTypes.SurfaceMesh)

    # Return the pick filter list
    return pickChoices


@apex_sdk.errorhandler
def ChooseExternalFile(sender, event):
    global times
    # Create a File open dialog
    dialog = OpenFileDialog()
    # Configure for single file selection
    dialog.Multiselect = False
    # Set up the file types you want to support
    dialog.Filter = ".csv Files|*.csv|.txt files|*.txt|Cradle XML Files|*.xml|VTK Poly Data 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():
        display_source_btn.IsEnabled = False
        selectedFile = dialog.FileName
        source_name_textbox.Text = ''
        dictionary = {}
        dictionary['filename'] = selectedFile
        apex_sdk.runScriptFunction(os.path.join(current_file_path, "display_map_field.py"),
                                   "preview_external_file",
                                   dictionary, callback=CheckUserInput)
        selectedFile = dialog.FileName
        # source_name_textbox.Text = selectedFile
        times = time.time()


@apex_sdk.errorhandler
def HandleTolCheck(sender, event):
   if sender.IsChecked:
      TolTextBox.Visibility = System.Windows.Visibility.Visible
   else:
      TolTextBox.Visibility = System.Windows.Visibility.Collapsed


@apex_sdk.errorhandler
def HandleTargetChange(sender, event):
    if not System.String.IsNullOrEmpty(sender.Text):
         map_source_to_target_btn.IsEnabled = True
         load_panel.IsEnabled = True
         mapping_stack_panel.Visibility = System.Windows.Visibility.Visible
    else:
         map_source_to_target_btn.IsEnabled = False
         load_panel.IsEnabled = False
         mapping_stack_panel.Visibility = System.Windows.Visibility.Collapsed

@apex_sdk.errorhandler
def DisplayField(sender, event):
    global times
    dictionary = {}
    dictionary['field_file_name'] = source_name_textbox.Text
    dictionary['times'] = times
    dictionary['field'] = field_type_combo.SelectedItem.Content
    dictionary['units'] = units_combo.SelectedItem.Content

    # (ComboBoxItem)
    # comboBox1.SelectedItem).Content.ToString();
    apex_sdk.runScriptFunction(os.path.join(current_file_path, "display_map_field.py"),
                               "display_external_field",
                               dictionary, callback=CheckUserInput)


@apex_sdk.errorhandler
def TargetEntitiesFocus(sender, event):
    global tselect
    map_field_tool_property_panel.ShowPickChoice = True
    map_field_tool_property_panel.PickFilterList = setPickFilterListMeshTarget()
    map_source_to_target_btn.IsEnabled = True
    tselect = True


@apex_sdk.errorhandler
def SelectTarget():
    dictionary = {}
    apex_sdk.runScriptFunction(os.path.join(current_file_path, "display_map_field.py"),
                               "handle_target_selection",
                               dictionary,
                               UpdateTargetSelection)

@apex_sdk.errorhandler
def UpdateTargetSelection():
    global tselect
    outdict = apex_sdk.getScriptFunctionReturnData()
    tselect = False
    if outdict == None: return;
    if 'selected_entities' in outdict.keys():
        target_entities_textbox.Text = outdict['selected_entities']


@apex_sdk.errorhandler
def HandleMapSourceToTarget(sender, event):
    global current_mapping_algorithm
    mapping_inputs = {}
    mapping_inputs['source'] = source_name_textbox.Text
    mapping_inputs['algorithm'] = current_mapping_algorithm
    mapping_inputs['outerOnly'] = outer_checkbox.IsChecked
    mapping_inputs['field'] = field_type_combo.SelectedItem.Content
    mapping_inputs['units'] = units_combo.SelectedItem.Content

    if TolBlock.IsChecked:
        mapping_inputs['tolerance'] = TolTextBox.Text
    else:
        mapping_inputs['tolerance'] = None

    if 'Preview' in sender.Content:
        mapping_inputs['method'] = 'Preview'
    else:
        mapping_inputs['method'] = 'Create'
        mapping_inputs['load_name'] = NameTextBox.Text

    apex_sdk.runScriptFunction(os.path.join(current_file_path, "display_map_field.py"),
                               "map_field_to_selected_entities",
                               mapping_inputs)

@apex_sdk.errorhandler
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

    global tselect
    if not tselect: return

    if 'Selection' in ToolGestureEventData.ges.gestureName:
        pass
#        print(ToolGestureEventData.ges.gestureName)

    if ToolGestureEventData.ges.gestureName in ['SingleSelection', 'SelectionExtendedComplete']:
#        print(ToolGestureEventData.ges.gestureName)
        SelectTarget()

    # 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)


# Function to handle the Import Button "Click" event
# This function gets called every time the Button is clicked
@apex_sdk.errorhandler
def HandleMappingOptions(sender, args):
    global current_mapping_algorithm
    if sender.Content == "Point cloud or mesh" and sender.IsChecked:
        current_mapping_algorithm = "Point cloud or mesh"
    elif sender.Content == "Mesh only" and sender.IsChecked:
        current_mapping_algorithm = "Mesh only"
    elif sender.Content == "Coarse to fine" and sender.IsChecked:
        current_mapping_algorithm = "Coarse to fine"


# Function to handle the Import Button "Click" event
# This function gets called every time the Button is clicked
@apex_sdk.errorhandler
def HandleImportButton(sender, args):
    # Create a File open dialog
    dialog = OpenFileDialog()

    # Configure for single file selection
    dialog.Multiselect = False

    # Set up the file types you want to support
    dialog.Filter = ".csv Files|*.csv|.txt files|*.txt|Cradle XML Files|*.xml|VTK Poly Data 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():
        selectedFile = dialog.FileName
        fileNameTextBox.Text = selectedFile
        dictionary = {}
        dictionary['field_file_name'] = selectedFile
        apex_sdk.runScriptFunction(os.path.join(current_file_path, "external_field_reader.py"),
                                   "display_external_field",
                                   dictionary)
