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



#setting pre-defined properties of tool_propertyContainer
def getUIContent():
    my_toolProperty = apex_sdk.ToolPropertyContainer()

    my_toolProperty.TitleText = "Composite Design Explorer"

    file_path = os.path.dirname(os.path.realpath(__file__))
    icon_path = os.path.join(file_path, (file_path), r'..\\res\\_Icon_SimCRAFT.png')
    my_toolProperty.TitleImageUriString=icon_path

    my_toolProperty.WorkFlowInstructions = """<HTML><BODY>
    <P STYLE=\"font-size:14;\">
    <SPAN>Instructions:</SPAN><br>
    <P STYLE=\"font-size:12;\">
    Step 1: Select failure theory from pulldown (Default Hill)<br><br>
    Step 2: Select tick boxes for plots wanted<br><br>
    Step 3: select Element(s) to be analysed</span><br><br>
    Step 4: Select green tick to run</span><br><br>
    <P STYLE=\"font-size:14;\">
    Notes: <br>
    <P STYLE=\"font-size:12;\"<b>
    plots can be saved as picture files <br><br>
    Questions or suggestions contact: MSC Support<br>
    </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))

    my_toolProperty.ToolPropertyContent = getCustomToolPropertyContent()

    # define pickFiterTools
    my_toolProperty.ShowPickChoice = True
    my_toolProperty.IsCustomTool = True
    # setPickFilterTools()
    my_toolProperty.PickFilterList = setPickFilterTools()

    return my_toolProperty


def getCustomToolPropertyContent():

    my_Grid = WPFControls.Grid()

    nRows = 13
    nCols = 3
    createLayout(my_Grid, nRows, nCols)
    iRow = iCol = 0

# global nameTextBox
# nameTextBox = createDataBox(my_Grid, "Element: ", True, iRow, iCol)
# iRow += 1

    global failureComboBox
    failureComboBox = createComboBox(my_Grid, "Failure Theory:", ["Max Strain",
                                                                  "Hill",
                                                                  "Tsai-Wu"],
                                     1, iRow, iCol)
    iRow += 1

    global checkBox1
    checkBox1 = createCheckBox(my_Grid,"Membrane Stiffness",True,iRow,iCol)
    iRow += 1
    #return my_Grid

    global checkBox2
    checkBox2= createCheckBox(my_Grid,"Bending Stiffness",True,iRow,iCol)
    iRow += 1
    # return my_Grid

    global checkBox3
    checkBox3= createCheckBox(my_Grid,"Membrane Failure",True,iRow,iCol)
    iRow += 1
    # return my_Grid

    global checkBox4
    checkBox4= createCheckBox(my_Grid,"Bending Failure",True,iRow,iCol)
    iRow += 1
    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 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 createCheckBox(parent, title, value, row, col):
    checkBox = WPFControls.CheckBox()
    checkBox.Content = title
    WPFControls.Grid.SetRow(checkBox, row)
    WPFControls.Grid.SetColumn(checkBox, col)
    if value==True:
        checkBox.IsChecked = System.Nullable[System.Boolean](True)

    parent.Children.Add(checkBox)

    return checkBox


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


# set pickFilters
# some pick choices are commented out
def setPickFilterTools():
    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.Element2D)
    return pickChoices


@apex_sdk.errorhandler
def HandleApplyButton():
    # Create a Dictionary to store the user defined tool data
    dictionary = {}

    dictionary["failureTheory"] = failureComboBox.Text
    dictionary["membraneStiffness"] = checkBox1.IsChecked
    dictionary["bendingStiffness"] = checkBox2.IsChecked
    dictionary["membraneStrength"] = checkBox3.IsChecked
    dictionary["bendingStrength"] = checkBox4.IsChecked

# dictionary["name"]             = nameTextBox.Text
# dictionary["material"]         = material

    file_path = os.path.dirname(os.path.realpath(__file__))
    script_path = os.path.join(file_path, 'CDE.py')

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


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