#
# 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 cfutils
import cfui
import cfmodel

import apex_sdk

import os
import sys
import shutil

import System
import System.Windows.Controls as WPFControls

def cfCopyFile(source, dest):
    result = dest
    
    try:
        if os.path.isfile(dest) == False:
            shutil.copyfile(source, dest)
        else:
            path = os.path.dirname(dest)
            base = os.path.basename(dest)
            name, extension = os.path.splitext(base)

            for i in range(100):
                filenameDest = path + os.sep + name + "_" + str(i) + extension
                if os.path.isfile(filenameDest) == False:
                    shutil.copyfile(source, filenameDest)
                    result = filenameDest
                    break

    except Exception as e:
        pass
        
    return result


class CfPropertyContent:
    appVersions = []
    cmbVersions = None
    cmbTemplates = None
    workingDirectory = None
    projectName = None

    def create(self):
        self.appVersions = cfmodel.getCAEfatigueVersions()
        if self.appVersions == None or len(self.appVersions) == 0:
            # If we can't find any versions we'll notify the user
            grid = cfui.createGrid(["auto"], ["*"])

            cfui.createLabel("No versions detected, please install CAEfatigue", 0, 0, grid)

            return grid

        # Create grid

        grid = cfui.createGrid(["auto", "auto", "auto"], 
            ["auto", "*"])

        # Versions
        cfui.createLabel("Version", 0, 0, grid)

        self.cmbVersions = cfui.createComboBox(
            [x.title for x in self.appVersions],
            0, 1, grid)
        self.cmbVersions.Tag = self.appVersions
        self.cmbVersions.SelectionChanged += self.onVersionChanged

        # Templates
        cfui.createLabel("Template", 1, 0, grid)
   
        self.cmbTemplates = cfui.createComboBox(["None" ], 1, 1, grid)

        # Start button
        btnStart = cfui.createButton("Start", self.onStart, 2, 0, grid)
        btnStart.Margin = cfui.getMargin(0.0, 10.0, 0.0, 10.0)
        btnStart.ToolTip = "Start CAEfatigue"
        WPFControls.Grid.SetColumnSpan(btnStart, 2)

        # Default selections
        if len(self.appVersions) > 0:
            self.cmbVersions.SelectedIndex = len(self.appVersions) - 1

        return grid


    def onVersionChanged(self, source, args):
        index = source.SelectedIndex

        self.cmbTemplates.Items.Clear()
    
        self.cmbTemplates.Items.Add("")

        for t in self.appVersions[index].templates:
            self.cmbTemplates.Items.Add(t.name)

    
    def onStart(self, source, args):
        try:
            indexVersion = self.cmbVersions.SelectedIndex
            indexTemplate = self.cmbTemplates.SelectedIndex

            version = self.appVersions[indexVersion]

            filename = None

            # Copy the template over to the current working path and open 
            if indexTemplate > 0:

                templatePath = version.templates[indexTemplate-1].path
                
                _, templateExtension = os.path.splitext(templatePath)

                filename = self.workingDirectory + self.projectName + os.sep + self.projectName + "_cf" + templateExtension

                filename = cfCopyFile(templatePath, filename)

            cfutils.runCAEfatigue(version.path, filename)

        except Exception as e:
            pass
    

    def setApplicationPath(self):
        result = apex_sdk.getScriptFunctionReturnData()

        self.workingDirectory =  result["path"].replace("/", os.sep)
        self.projectName = result["name"]
        

def getUIContent():
    
    toolProperty = apex_sdk.ToolPropertyContainer()

    toolProperty.ToolPropertyContent = getToolPropertyContent()
    toolProperty.TitleText = "CAEfatigue"
    toolProperty.WorkFlowInstructions = "Export to BDF, run Nastran, start CAEfatigue"
    toolProperty.IsAppliedVisible = False

    return toolProperty


def getToolPropertyContent():

    cfcontrol = CfPropertyContent()
    
    apex_sdk.runScriptFunction( cfutils.cfgetScriptPath() + os.sep + "cfapi.py", "cfgetCurrentProjectPath", callback=cfcontrol.setApplicationPath)

    return cfcontrol.create()

