#
# 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.
#
# MSC Apex - Material Database Tool using Scripts
# coding: utf-8

# Author: Javier Lázaro
# Revised by: Javier Lázaro
# Revision History
# Date         Change                                 By
# 2020-11-25   Original code                          Javier Lázaro
import sys
import os

src_dir = os.path.dirname(os.path.realpath(__file__))
# res_dir = os.path.join(os.path.dirname(src_dir), "res")
# req_path = os.path.join(res_dir, "requirements.txt")
xls_path =  os.path.join(src_dir, "MyMaterials.xls")



def import_error():
    print("Requirements not met: modules missing")
    print()
    print("To install necessary modules use next commands on your Command Prompt (**with administrator privileges):")
    print()
    # print('&"'+sys.executable+'" -m pip install pandas')
    # print('&"'+sys.executable+'" -m pip install xlrd')
    print('"C:\Path_to_MSCApex\python3\python.exe" -m pip install pandas')
    print('"C:\Path_to_MSCApex\python3\python.exe" -m pip install xlrd')
    sys.exit()
try:
    from pandas import read_excel, DataFrame, read_csv
except ImportError:
    import_error()

import apex

apex.setScriptUnitSystem(unitSystemName = r'''mm-t-s-N-K''')




def read_xls(dictionary={}):
    apex.disableShowOutput()
    dfs = read_excel(xls_path, sheet_name = None, keep_default_na = False)
    #ironpython cant handle dataframes and they must be converted to dictionary
    ret_dict = {}
    for key, df in dfs.items():
        if "Iso" in key or "Ortho" in key:
            ret_dict[key] = df.to_dict("index")
    return ret_dict

def importSelectedIso(dictionary={}):
    apex.disableShowOutput()
    df = read_excel(xls_path, sheet_name = dictionary["sheet"], keep_default_na = False)

    matNames = dictionary["matNames"]
    matNames = matNames[1:-1]
    matNames = matNames.replace("'", "")
    matNames = matNames.split(", ")
    if not matNames[0]: return
    matNames = list(matNames)

    df = df.set_index('Name')

    for matName in matNames:
        mat = df.loc[matName]
        materialIso = apex.catalog.createMaterial(
            name = matName,
            description = ""
            )
        print()
        print("Loading: "+matName)
        if mat.Elastic_Modulus:
            try:
                materialIso.update( elasticModulus = mat.Elastic_Modulus+0.0 )
            except:
                print("Error loading elasticModulus. Check syntax.")
        if mat.Poisson_Ratio:
            try:
                materialIso.update( poissonRatio = mat.Poisson_Ratio+0.0 )
            except:
                print("Error loading poissonRatio. Check syntax.")
        if mat.Density:
            try:
                materialIso.update( density = mat.Density+0.0 )
            except:
                print("Error loading density. Check syntax.")
        if mat.StrDmpCoef:
            try:
                materialIso.update( dampingCoefficient = mat.StrDmpCoef+0.0 )
            except:
                print("Error loading dampingCoefficient. Check syntax.")
        if mat.TEC:
            try:
                materialIso.update( thermalExpansionCoeff = mat.TEC+0.0 )
            except:
                print("Error loading Thermal Expansion Coefficient. Check syntax.")

        dict = {}
        if mat.Tension_Failure:
            try:
                materialIso.update( failureLimitsIsotropic = {'stressLimitTension' : mat.Tension_Failure+0.0} )
            except:
                print("Error loading stressLimitTension. Check syntax.")
        if mat.Compression_Failure:
            try:
                materialIso.update( failureLimitsIsotropic = {'stressLimitCompression' : mat.Compression_Failure+0.0} )
            except:
                print("Error loading stressLimitCompression. Check syntax.")
        if mat.Shear_Failure:
            try:
                materialIso.update( failureLimitsIsotropic = {'stressLimitShear' : mat.Shear_Failure+0.0} )
            except:
                print("Error loading stressLimitShear. Check syntax.")


def importSelectedOrtho(dictionary={}):
    apex.disableShowOutput()
    df = read_excel(xls_path, sheet_name = dictionary["sheet"], keep_default_na = False)

    matNames = dictionary["matNames"]
    matNames = matNames[1:-1]
    matNames = matNames.replace("'", "")
    matNames = matNames.split(", ")
    if not matNames[0]: return
    matNames = list(matNames)

    df = df.set_index('Name')

    for matName in matNames:
        mat = df.loc[matName]
        materialOrtho = apex.catalog.createMaterial(
            name = matName,
            description = "",)
        materialOrtho.update(
            materialType = apex.attribute.MaterialType.Orthotropic,
        )
        print()
        print("Loading: "+matName)
        try:
            materialOrtho.update( elasticityOrthotropic2D = {
            'elasticModulusX' : mat.Ex+0.0,
            'elasticModulusY' : mat.Ey+0.0,
            'shearModulusXY' : mat.Gxy+0.0,
            'shearModulusYZ' : mat.Gyz+0.0,
            'shearModulusXZ' : mat.Gzx+0.0,
            })
        except:
            print("Error loading elastic properties. Check syntax. or missing property.")
        try:
            materialOrtho.update( poissonRatio = mat.NUxy+0.0 )
        except:
            print("Error loading Poisson Ratio (NUxy). Check syntax.")
        try:
            materialOrtho.update( density = mat.Density+0.0 )
        except:
            print("Error loading density. Check syntax.")
        try:
            materialOrtho.update( dampingCoefficient = mat.StrDmpCoef+0.0 )
        except:
            print("Error loading dampingCoefficient. Check syntax.")

        try:
            materialOrtho.update( thermalExpansionCoeffOrthotropic2D = {
                        'thermalExpansionCoeffX' : mat.TEC_X+0.0,
                        'thermalExpansionCoeffY' : mat.TEC_Y+0.0, }
                        )
        except:
            print("Error loading Thermal Expansion Coefficients. Fill all or None. Check syntax.")

        try:
            materialOrtho.update( failureLimitsOrthotropic2D = {
                        'stressLimitTensionX' : mat.Tension_Failure_X+0.0,
                        'stressLimitTensionY' : mat.Tension_Failure_Y+0.0,
                        'stressLimitCompressionX' : mat.Compression_Failure_X+0.0,
                        'stressLimitCompressionY' : mat.Compression_Failure_Y+0.0,
                        'stressLimitInplaneShear' : mat.Shear_Failure+0.0, }
                        )
        except:
            print("Error loading Failure Stresses. Fill all or None. Check syntax.")
