#
# 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.
#
# Author: Larry Pearce
# Revised by: Larry Pearce
# Revision History
# Date         Change                                 By
# 2020-10-12   Original code                          Larry Pearce

import os
import apex_sdk

import System
import System.Windows.Controls as WPFControls


def getUIContent():

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

    my_toolProperty.TitleText = "Manage Parts & Assemblies 1.0"

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


    my_toolProperty.WorkFlowInstructions = """<HTML><BODY><P STYLE=\"font-size:10;\"><SPAN>Deletes empty Parts and Assemblies</SPAN></P>
    <P><SPAN> </SPAN></P>
    <P><SPAN>Removes empty Parts and Assemblies.  This script is not recursive, so you may need to execute it multiple times to remove all empty Assemblies.</SPAN></P>
    <P><SPAN>This script also collapses Assemblies that only contain a single Part.  The Part is moved to the parent Assembly for the collapsed Assembly.</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>"""

    my_toolProperty.AppliedCommand = apex_sdk.ActionCommand(System.Action(HandleApplyButton))

    #my_toolProperty.ShowPickChoice = True
    #my_toolProperty.PickFilterList = setPickFilterList()

    return my_toolProperty


def setPickFilterList():
    #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)

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

    #Return the pick filter list
    return pickChoices


def getCustomToolPropertyContent():

    my_Grid = WPFControls.Grid()

    createLayout(my_Grid, 15, 2)

    global allAssembliesTextBox
    global emptyAssembliesTextBox
    global allPartsTextBox
    global emptyPartsTextBox
    global subAssembliesTextBox
    global renamePart_Toggle

    iRow = iCol = 0
    allPartsTextBox = createDataBox(my_Grid, "All Parts:", "", iRow, iCol)

    iRow += 1
    emptyPartsTextBox = createDataBox(my_Grid, "Empty Parts:", "", iRow, iCol)
    
    iRow += 1
    deleteEmptyPartsBtn = WPFControls.Button()
    deleteEmptyPartsBtn.Content="Delete Empty Parts"
    deleteEmptyPartsBtn.Click+=HandleDeleteEmptyPartsBtn
    WPFControls.Grid.SetColumnSpan(deleteEmptyPartsBtn, 2)
    WPFControls.Grid.SetRow(deleteEmptyPartsBtn, iRow)
    WPFControls.Grid.SetColumn(deleteEmptyPartsBtn, iCol)
    deleteEmptyPartsBtn.Margin = System.Windows.Thickness(5.)
    my_Grid.Children.Add(deleteEmptyPartsBtn)
    
    iRow += 1
    sep = WPFControls.Separator()
    WPFControls.Grid.SetRow(sep, iRow)
    WPFControls.Grid.SetColumnSpan(sep, 2)
    my_Grid.Children.Add(sep)
    
    iRow += 1
    allAssembliesTextBox = createDataBox(my_Grid, "All Assemblies:", "", iRow, iCol)

    iRow += 1
    emptyAssembliesTextBox = createDataBox(my_Grid, "Empty Assemblies:", "", iRow, iCol)
    
    iRow += 1
    deleteEmptyAssysBtn = WPFControls.Button()
    deleteEmptyAssysBtn.Content="Delete Empty Assemblies"
    deleteEmptyAssysBtn.Click+=HandleDeleteEmptyAssysBtn
    WPFControls.Grid.SetColumnSpan(deleteEmptyAssysBtn, 2)
    WPFControls.Grid.SetRow(deleteEmptyAssysBtn, iRow)
    WPFControls.Grid.SetColumn(deleteEmptyAssysBtn, iCol)
    deleteEmptyAssysBtn.Margin = System.Windows.Thickness(5.)
    my_Grid.Children.Add(deleteEmptyAssysBtn)
    
    iRow += 1
    sep = WPFControls.Separator()
    WPFControls.Grid.SetRow(sep, iRow)
    WPFControls.Grid.SetColumnSpan(sep, 2)
    my_Grid.Children.Add(sep)
    
    iRow += 1
    subAssembliesTextBox = createDataBox(my_Grid, "Sub-Assemblies w/ 1 Part:", "", iRow, iCol)

    iRow += 1
    renamePart_Toggle = createCheckBox2(my_Grid, "Rename Part with Assembly Name", iRow, iCol)


    iRow += 1
    collapseSubAssysBtn = WPFControls.Button()
    collapseSubAssysBtn.Content="Collapse Single Part Sub-Assemblies"
    collapseSubAssysBtn.Click+=HandleCollapseSubAssysBtn
    WPFControls.Grid.SetColumnSpan(collapseSubAssysBtn, 2)
    WPFControls.Grid.SetRow(collapseSubAssysBtn, iRow)
    WPFControls.Grid.SetColumn(collapseSubAssysBtn, iCol)
    collapseSubAssysBtn.Margin = System.Windows.Thickness(5.)
    my_Grid.Children.Add(collapseSubAssysBtn)
    
    HandleApplyButton()

    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)
    textBlock.Margin = System.Windows.Thickness(5.)

    textBox =WPFControls.TextBox()
    textBox.Margin = System.Windows.Thickness(5.)
    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 createCheckBox2(parent, label, row, col):

    checkBox = WPFControls.CheckBox()
    checkBox.Content = label
    WPFControls.Grid.SetRow(checkBox, row)
    WPFControls.Grid.SetColumn(checkBox, col)

    parent.Children.Add(checkBox)

    return checkBox



@apex_sdk.errorhandler
def HandleApplyButton():

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

    apex_sdk.runScriptFunction(script_path, "main", callback=UpdateTextBoxes)


#This function receives data from the Script API function and updates the Tool UI 
@apex_sdk.errorhandler
def UpdateTextBoxes():
    ret_dict = apex_sdk.getScriptFunctionReturnData()

    allPartsTextBox.Text        = ret_dict["allParts"]
    emptyPartsTextBox.Text      = ret_dict["emptyParts"]
    allAssembliesTextBox.Text   = ret_dict["allAssemblies"]
    emptyAssembliesTextBox.Text = ret_dict["emptyAssemblies"]
    subAssembliesTextBox.Text   = ret_dict["singlePartSubAssemblies"]


@apex_sdk.errorhandler
def HandleDeleteEmptyPartsBtn(sender, args):
    dictionary = {}

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

    HandleApplyButton()



@apex_sdk.errorhandler
def HandleDeleteEmptyAssysBtn(sender, args):
    dictionary = {}

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

    HandleApplyButton()



@apex_sdk.errorhandler
def HandleCollapseSubAssysBtn(sender, args):
    global renamePart_Toggle
    dictionary = {}

    dictionary["renamePart"] = renamePart_Toggle.IsChecked

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

    HandleApplyButton()
