#
# 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
from Microsoft.Win32 import SaveFileDialog


global utils_path
file_path = os.path.dirname(os.path.realpath(__file__))
utils_path= os.path.dirname(os.path.realpath(file_path)) + "\\res"

def getUIContent():

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

	my_toolProperty.TitleText = "Automated Report"

	file_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
	my_toolProperty.TitleImageUriString = file_path + "\\res\\icon_report.png"

	my_toolProperty.WorkFlowInstructions = """<HTML><BODY><P STYLE=\"font-size:10;\"><SPAN>Generate automatic report for the current model.</SPAN></P>
	<P><SPAN> </SPAN></P>
	<HTML><BODY><P STYLE=\"font-size:10;\"><SPAN>Please read the documentation to properly use the utility.</SPAN></P>
	<P><SPAN> </SPAN></P>
	<P STYLE=\"font-size:10;\"><SPAN>Send questions to javier.lazaroortega@hexagon.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))

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



	return my_toolProperty

def createTextBlock(parent, text, iRow, iCol):
	textBlock = WPFControls.TextBlock()
	textBlock.Text = text

	textBlock.Margin = System.Windows.Thickness(5.)

	WPFControls.Grid.SetRow(textBlock, iRow)
	WPFControls.Grid.SetColumn(textBlock, iCol)
	parent.Children.Add(textBlock)

	return textBlock

def updateComboBox(comboBox, comboItems):

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

def createEmptyRow(parent, iRow):
	textBlock = WPFControls.TextBlock()
	textBlock.Text = ""
	WPFControls.Grid.SetRow(textBlock, iRow)
	WPFControls.Grid.SetColumn(textBlock, 0)

	parent.Children.Add(textBlock)

	return

def getCustomToolPropertyContent():
	global dictionary
	global utils_path

	my_Grid = WPFControls.Grid()

	createLayout(my_Grid, 5, 2)

	iRow = 0
	iCol = 0

	###########
	global Tree
	Tree = createCheckBox(my_Grid, "Tree", True, iRow, 0)
	###########
	global Node_Count
	Node_Count = createCheckBox(my_Grid, "Node Count", True, iRow, 1)
	iRow += 1
	###########

	###########
	global Element_Count
	Element_Count = createCheckBox(my_Grid, "Element Count", True, iRow, 0)
	###########
	global Panels
	Panels = createCheckBox(my_Grid, "Panels", True, iRow, 1)
	iRow += 1
	###########

	# ---- Chequeos ----

	global resultsComboBox, resultsComboTextBlock
	resultsComboTextBlock = createTextBlock(my_Grid, "Results:", iRow, 0)
	resultsComboBox       = createComboBox2(my_Grid, iRow, 1)
	iRow += 1

	resultsComboTextBlock.Visibility = System.Windows.Visibility.Visible
	resultsComboBox.Visibility       = System.Windows.Visibility.Visible

	# Get both scenarios and events
	file_path = os.path.dirname(os.path.realpath(__file__))
	script_path_parts= os.path.join(file_path, 'getScenariosAndEvents.py')
	apex_sdk.runScriptFunction(script_path_parts, "main", callback=getNewScenariosCB)



	###########
	# global timeStepTextBox
	# timeStepTextBox = createDataBox(my_Grid, "Time Step:", "1.e-3", iRow, iCol)
	# iRow += 1
	###########
	global reportPath
	reportPath = docxBrowser(my_Grid, "Save as", iRow, iCol)
	iRow += 1

	#Return the Grid

	return my_Grid

def scenariosComboBoxCB(sender, event):
	global scenariosComboBox
	global eventComboBox
	global eventNameL
	global scenarioNameL

	choices = scenariosComboBox.SelectedValue.ToString().split(":")
	_scenario_name = choices[len(choices)-1].lstrip().rstrip()
	# # # get list of scenarios and events

	if 1==1:
		ret_dict = apex_sdk.getScriptFunctionReturnData()
		scenarios = ret_dict["ScenarioList"]
		eventL = ret_dict["EventL"]

	my_eventNameL=[]
	n=0
	while n < len(scenarios):

		if scenarios[n] == _scenario_name:
			my_eventNameL=eventL[n].split('¤')
		n+=1

	scenarioNameL=scenarios
	eventNameL=eventL

	refreshComboBox(eventComboBox, my_eventNameL)

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 createComboBox2(parent, iRow, iCol):
	comboBox = WPFControls.ComboBox()

	comboBox.Margin = System.Windows.Thickness(5.)

	WPFControls.Grid.SetRow(comboBox, iRow)
	WPFControls.Grid.SetColumn(comboBox, iCol)

	parent.Children.Add(comboBox)

	return comboBox

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

	comboBox.SelectedIndex="0"

def updateComboBox2(comboBox, comboItems):
	n=0
	for comboItem in comboItems:
		item = WPFControls.ComboBoxItem()
		item.Content=comboItem
		comboBox.Items.Add(item)
		n+=1
	try:
		comboBox.SelectedIndex="0"
	except:
		pass
		print("could not set combobox index")

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

	textBox =WPFControls.TextBox()
	WPFControls.Grid.SetRow(textBox, iRow)
	WPFControls.Grid.SetColumn(textBox, iCol+1)
	textBox.Text=value

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

	return textBox

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

	parent.Children.Add(textBox)

	return textBox


def createCheckBox(parent, title, active, iRow, iCol):
	myWrapPanel = WPFControls.WrapPanel()
	myWrapPanel.Orientation = WPFControls.Orientation.Vertical

	CheckBox = WPFControls.CheckBox()
	CheckBox.Content = title
	myWrapPanel.Children.Add(CheckBox)

	WPFControls.Grid.SetRow(myWrapPanel, iRow)
	WPFControls.Grid.SetColumn(myWrapPanel, iCol)
	CheckBox.IsChecked = System.Nullable[System.Boolean](active)

	parent.Children.Add(myWrapPanel)

	return CheckBox



#Function to handle the Import Button "Click" event
#This function gets called every time the Button is clicked
@apex_sdk.errorhandler
def HandleSaveBtn(sender,args):

	#Create a File open dialog
	#dialog = OpenFileDialog()
	dialog = SaveFileDialog()

	#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 docxBrowser(parent, title, row, col):
    textBox =WPFControls.TextBox()
    WPFControls.Grid.SetRow(textBox, row)
    WPFControls.Grid.SetColumn(textBox, col)

    def button(sender,args):
        dialog = SaveFileDialog()
        #Configure for single file selection
        dialog.Multiselect = False
        # #Set up the file types you want to support
        dialog.Filter = " (*.docx) | *.docx"
        dialog.DefaultExt = "*.docx"
        if dialog.ShowDialog():
            textBox.Text = dialog.FileName

    BtnSave = WPFControls.Button()
    BtnSave.Content = title
    WPFControls.Grid.SetRow(BtnSave, row)
    WPFControls.Grid.SetColumn(BtnSave,col+1)
    BtnSave.Click += button


    parent.Children.Add(textBox)
    parent.Children.Add(BtnSave)
    return textBox


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

	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 getNewScenariosCB():
	global resultsComboBox
	global eventNameL
	global scenarioNameL
	global eventComboBox

	ret_dict = apex_sdk.getScriptFunctionReturnData()
	scenarios=[] #not using default load case


	# Build Scenario list
	try:
		tmp = ret_dict["ScenarioList"]
	except:
		print("No scenarios found")
		tmp=[]

	for item in tmp:
		scenarios.append(item)

	updateComboBox2(resultsComboBox, reversed(scenarios) )

	scenarioNameL=scenarios
	# Get the events Dict

	# Build Event list
	try:
		eventNameL = ret_dict["EventL"]
	except:
		print("No Events Found")
		eventNameL=[]
