#
# 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 = "Add Ply Stack"
    file_path = os.path.dirname(os.path.realpath(__file__))
    icon_path = os.path.join(file_path, (file_path), r'..\\res\\_Icon_stack2.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: Input ply thickness in default length units (Default 1.0)<br><br>
    Step 2: Input ply angles in sequence separated by “/” (Default 0/45/90/-45)</span><br><br>
    Step 3: Select material from pull down list</span><br><br>
    Step 4: Selecting appropriate filter, select faces or surfaces to be covered.</span><br><br>
    Step 5: Select green tick to run</span><br><br>
    <P STYLE=\"font-size:14;\">
    Notes: <br>
    <P STYLE=\"font-size:12;\"<b>>
    Plies are coloured according to their angle. <br>
    -22.5 to 22.5 Red.<br>
    67.5 to 112.5 Green <br>
    all other plies Blue <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():

    global thicknessTextBox
    global materialTextBox
    global anglesTextBox
    global nameTextBox
    global materialComboBox

    my_Grid = WPFControls.Grid()

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

    thicknessTextBox = createDataBox(my_Grid, "Thickness: ", "1.0", iRow, iCol)
    iRow += 1
    anglesTextBox = createDataBox(my_Grid, "Ply Angles: ",
                                  "0/45/90/-45", iRow, iCol)
    iRow += 1

    materials = {}
    file_path = os.path.dirname(os.path.realpath(__file__))
    script_path = os.path.join(file_path, 'addPlyStack.py')
    apex_sdk.runScriptFunction(script_path, "get_materials", callback=getMatls)
    materialComboBox = createComboBox(my_Grid,
                                      "Material:", materials, 1, 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 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)

    # Assembly and part
    # pickChoices.Add(apex_sdk.PickFilterTypes.Assembly)
    #  pickChoices.Add(apex_sdk.PickFilterTypes.Part)

    # Bodies
    # pickChoices.Add(apex_sdk.PickFilterTypes.SolidMesh)
    # pickChoices.Add(apex_sdk.PickFilterTypes.Solid)
    # pickChoices.Add(apex_sdk.PickFilterTypes.SurfaceMesh)
    pickChoices.Add(apex_sdk.PickFilterTypes.Surface)
    # pickChoices.Add(apex_sdk.PickFilterTypes.CurveMesh)
    # pickChoices.Add(apex_sdk.PickFilterTypes.Curve)
    # pickChoices.Add(apex_sdk.PickFilterTypes.Point)

    # features
    # pickChoices.Add(apex_sdk.PickFilterTypes.CellMesh)
    # pickChoices.Add(apex_sdk.PickFilterTypes.FaceMesh)
    # pickChoices.Add(apex_sdk.PickFilterTypes.EdgeMesh)
    # pickChoices.Add(apex_sdk.PickFilterTypes.Cell)
    # pickChoices.Add(apex_sdk.PickFilterTypes.VertexMesh)

    # Lower Dimensional Entities
    # pickChoices.Add(apex_sdk.PickFilterTypes.Element3D)
    # pickChoices.Add(apex_sdk.PickFilterTypes.Element2D)
    pickChoices.Add(apex_sdk.PickFilterTypes.Face)
    # pickChoices.Add(apex_sdk.PickFilterTypes.MeshSeed)
    # pickChoices.Add(apex_sdk.PickFilterTypes.Element1D)
    # pickChoices.Add(apex_sdk.PickFilterTypes.Edge)
    # pickChoices.Add(apex_sdk.PickFilterTypes.SeedPoint)
    # pickChoices.Add(apex_sdk.PickFilterTypes.Node)
    # pickChoices.Add(apex_sdk.PickFilterTypes.Vertex)

    # Sub Lower Dimensional Entities
    # pickChoices.Add(apex_sdk.PickFilterTypes.ElementEdge)
    # pickChoices.Add(apex_sdk.PickFilterTypes.ElementFace)

    # Interactions and connections
    # pickChoices.Add(apex_sdk.PickFilterTypes.DiscreteTie)
    # pickChoices.Add(apex_sdk.PickFilterTypes.Connector)
    # pickChoices.Add(apex_sdk.PickFilterTypes.EdgeTie)
    # pickChoices.Add(apex_sdk.PickFilterTypes.Joint)
    # pickChoices.Add(apex_sdk.PickFilterTypes.Glue)

    # LBCs
    # pickChoices.Add(apex_sdk.PickFilterTypes.Pressure)
    # pickChoices.Add(apex_sdk.PickFilterTypes.Gravity)
    # pickChoices.Add(apex_sdk.PickFilterTypes.Constraint)
    # pickChoices.Add(apex_sdk.PickFilterTypes.ForceMoment)
    # pickChoices.Add(apex_sdk.PickFilterTypes.EnforcedMotion)

    # Attributes and other objects
    # pickChoices.Add(apex_sdk.PickFilterTypes.CompositeZone)
    # pickChoices.Add(apex_sdk.PickFilterTypes.LayeredPanel)
    # pickChoices.Add(apex_sdk.PickFilterTypes.InterfacePoint)
    # pickChoices.Add(apex_sdk.PickFilterTypes.PointMass)
    # pickChoices.Add(apex_sdk.PickFilterTypes.BeamSpan)
    # pickChoices.Add(apex_sdk.PickFilterTypes.Offset)

    # Sensors
    # pickChoices.Add(apex_sdk.PickFilterTypes.MotionEnvelopeSensor)
    # pickChoices.Add(apex_sdk.PickFilterTypes.ClearanceSensor)
    # pickChoices.Add(apex_sdk.PickFilterTypes.CrossSectionSensor)
    # pickChoices.Add(apex_sdk.PickFilterTypes.PointSensor)

    # Coordinate system
    # pickChoices.Add(apex_sdk.PickFilterTypes.CoordinateSystem)

    # Tool Registration
    # Tool Name has to be the same
    # apex_sdk.PickFilterRegistration.RegisterTool("Auto Tie Nodes", pickChoices)
    return pickChoices


@apex_sdk.errorhandler
def HandleApplyButton():

    global thicknessTextBox
    global materialTextBox
    global anglesTextBox

    # Create a Dictionary to store the user defined tool data
    dictionary = {}

    dictionary["Material"] = materialComboBox.Text
    dictionary["Thickness"] = thicknessTextBox.Text
    dictionary["Angles"] = anglesTextBox.Text
    dictionary["Test"] = False


#    choices = materialComboBox.SelectedValue.ToString().split(":")
#    material = choices[len(choices)-1].lstrip().rstrip()

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

    file_path = os.path.dirname(os.path.realpath(__file__))
    script_path = os.path.join(file_path, 'addPlyStack.py')
    apex_sdk.runScriptFunction(script_path, "main", dictionary)


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


    # This function receives data from the Script API function and updates the Tool UI
@apex_sdk.errorhandler
def getMatls():
    global matlComboBox

    ret_dict = apex_sdk.getScriptFunctionReturnData()

    materials = ret_dict["matlList"]

    updateComboBox(materialComboBox, materials)


def updateComboBox(comboBox, comboItems):

    for comboItem in comboItems:
        item = WPFControls.ComboBoxItem()
        item.Content = comboItem
        comboBox.Items.Add(item)

    comboBox.SelectedIndex = "0"
