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


def getUIContent():

    my_toolProperty = apex_sdk.ToolPropertyContainer()
    my_toolProperty.ToolPropertyContent = getCustomToolPropertyContent()

    my_toolProperty.TitleText = "Fasteners from mwf/mcf 2.0"

    file_path = os.path.dirname(os.path.realpath(__file__))
    my_toolProperty.TitleImageUriString = os.path.join(os.path.dirname(file_path), r"res\auFromMWF.png")

    my_toolProperty.WorkFlowInstructions = """<HTML><BODY><P STYLE=\"font-size:10;\"><SPAN>Auto connects Parts via mwf file</SPAN></P>
    <P><SPAN> </SPAN></P>
    <P STYLE=\"font-size:10;\"><SPAN>Bushing properties are auto calculated from diameter, length, and material data.  The script 
    uses material properties for a material named: fastenerMatl.</SPAN></P>
    <P><SPAN> </SPAN></P>
    <P STYLE=\"font-size:10;\"><SPAN>Send questions, comments and Elvis sightings to larry.pearce@mscsoftware.com</SPAN></P></BODY></HTML>"""

    #handle apply button (green) click event
    my_toolProperty.AppliedCommand = apex_sdk.ActionCommand(System.Action(HandleApplyButton))
    # handle exit button (red) click event
    my_toolProperty.ExitCommand = apex_sdk.ActionCommand(System.Action(HandleExitButton))

    return my_toolProperty


#get tool property content
def getCustomToolPropertyContent():
    #Create a Grid
    my_Grid = WPFControls.Grid()

    createLayout(my_Grid, 5, 2)

    row = 0
    col = 0

    global fastenerTypeComboBox
    fastenerTypeComboBox = createComboBox(my_Grid, "Fastener Type:", ["Rigid Link", "Bushing", "Flexible Link"], 1, row, col)
    row += 1

    global diaTextBox
    diaTextBox = createDataBox(my_Grid, "Diameter: ", "0.2", row, col)
    row += 1
    global toleranceTextBox
    toleranceTextBox = createDataBox(my_Grid, "Tolerance: ", "0.3", row, col)
    row += 1

    global fileTextBox
    fileTextBox = createDataBox2(my_Grid, "", row, col)
    row += 1

    WPFControls.Grid.SetColumnSpan(fileTextBox, 2)

    importBtn = WPFControls.Button()
    importBtn.Content="Select mwf file ..."

    WPFControls.Grid.SetColumnSpan(importBtn, 2)

    WPFControls.Grid.SetRow(importBtn, row)
    WPFControls.Grid.SetColumn(importBtn, col)

    #Link a function to the Button "Click" event
    #This function will be called every time the Button is clicked
    importBtn.Click+=HandleimportBtn

    # Add the controls to the Gri
    my_Grid.Children.Add(importBtn)

    #Return the Grid
    return my_Grid


def createLayout(parent, numRows, numCols):
    for k in range(numRows):
        parent.RowDefinitions.Add(WPFControls.RowDefinition())
    for k in range(numCols):
        parent.ColumnDefinitions.Add(WPFControls.ColumnDefinition())


def createComboBox(parent, title, labels, selected, row, col):
    textBlock = WPFControls.TextBlock()
    textBlock.Text = title
    WPFControls.Grid.SetRow(textBlock, row)
    WPFControls.Grid.SetColumn(textBlock, col)

    parent.Children.Add(textBlock)

    comboBox = WPFControls.ComboBox()
    for label in labels:
        item = WPFControls.ComboBoxItem()
        item.Content=label
        comboBox.Items.Add(item)

    WPFControls.Grid.SetRow(comboBox, row)
    WPFControls.Grid.SetColumn(comboBox, col+1)

    if selected > len(labels): selected = 0
    comboBox.SelectedIndex=str(selected)

    parent.Children.Add(comboBox)

    return comboBox


def createDataBox(parent, title, value, row, col):
    textBlock = WPFControls.TextBlock()
    textBlock.Text = title
    WPFControls.Grid.SetRow(textBlock, row)
    WPFControls.Grid.SetColumn(textBlock, col)

    textBox =WPFControls.TextBox()
    WPFControls.Grid.SetRow(textBox, row)
    WPFControls.Grid.SetColumn(textBox, col+1)
    textBox.Text=value

    parent.Children.Add(textBlock)
    parent.Children.Add(textBox)

    return textBox


def createDataBox2(parent, value, row, col):
    textBox =WPFControls.TextBox()
    WPFControls.Grid.SetRow(textBox, row)
    WPFControls.Grid.SetColumn(textBox, col)
    textBox.Text=value

    parent.Children.Add(textBox)

    return textBox


#Function to handle the Import Button "Click" event
#This function gets called every time the Button is clicked
@apex_sdk.errorhandler
def HandleimportBtn(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 = "All Files  |*.*"
    #dialog.Filter = "MWF Files  |*.mwf* | All Files  |*.*"

    #Display the dialog
    #If it returns anything
    #   get the file name
    #   display it on the text nox
    if dialog.ShowDialog():
        selectedFile = dialog.FileName
        fileTextBox.Text = selectedFile


@apex_sdk.errorhandler
def HandleApplyButton():
    file_path = os.path.dirname(os.path.realpath(__file__))
    script_path= os.path.join(file_path, 'auFromMWF.py')
    # Create a Dictionary to store the user defined tool data
    dictionary = {}

    choices = fastenerTypeComboBox.SelectedValue.ToString().split(":")
    choice = choices[len(choices)-1].lstrip().rstrip()

    dictionary["fastenerType"] = choice
    dictionary["tolerance"]    = toleranceTextBox.Text
    dictionary["diameter"]     = diaTextBox.Text
    dictionary["fspec"]        = fileTextBox.Text

    apex_sdk.runScriptFunction(script_path, "main", dictionary)


# exit button (red) from tool header
@apex_sdk.errorhandler
def HandleExitButton():
    print("HandleExitButton")

