#
# 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 apex
from apex.construct import Point3D, Point2D

import os
import sys
import importlib
import subprocess

pathDir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))

if not pathDir in sys.path:
    sys.path.insert(0, pathDir)
    print('inserted ' + pathDir + ' into sys.path')

#==============================================================================
def read_settings(settings_file, tmp_h=""):

    silent_flag = True
    #
    # settings_file=r'C:\Users\e7390\Documents\Predator\Topics\Scripting\Sample_files\UtilityUserSettings.xml'
    inf = open(settings_file, 'r')
    lines = inf.readlines()
    inf.close()
    keys = []
    SettingsD = {}
    n = 0
    while n < len(lines):
        if lines[n].find('<') > -1 and  lines[n].find('\\') < 0 and lines[n].find('/') < 0:
            # found start tag
            # print lines[n]
            tmp = lines[n].strip().replace('<', '').replace('>', '')
            # print tmp
            endtag = "<\\" + tmp + ">"
            endtag2 = "</" + tmp + ">"
            # print endtag
            n += 1
            SettingsD[tmp] = {}
            while lines[n].find(endtag) < 0 and lines[n].find(endtag2) <0 :
                #while lines[n].find(endtag) < 0 :
                if lines[n].find('=') > 1:
                    newkey = lines[n].strip().split('=')[0]
                    SettingsD[tmp][newkey] = lines[n].strip().split('=')[1]
                    n += 1
                elif lines[n].find('#') == 0:
                    continue
                else:
                    # not a valid settnigs command
                    #print "Not a valid settngs command: " + lines[n]
                    n += 1
                #print(lines[n])
        n += 1

    # supress write out of all settings

    if silent_flag != True:
        if tmp_h != -1:
            print("====")
            print("Following setting groups detected:")

        for item in reversed(sorted(SettingsD.keys())):
            if tmp_h != -1:
                print("==== " + item + "   " + " ====")

            for key in list(SettingsD[item].keys()):
                if tmp_h != "" and tmp_h != -1:
                    print("%-16s : %-12s" % (key, SettingsD[item][key].strip()))
                elif tmp_h == -1:
                    continue
                else:
                    print("%-16s : %-12s" % (key, SettingsD[item][key].strip()))
    #
    return SettingsD

#==============================================================================
def write_proc_header(proc_file_h):

    # create header file
    if 1 == 1:

        proc_file_h.write("| Created by Apex 2021 \n")

        proc_file_h.write("*prog_option compatibility:prog_version:ment2020\n")
        proc_file_h.write("*prog_analysis_class structural\n")
        proc_file_h.write("*prog_use_current_job on\n")
        proc_file_h.write("*set_default_length_unit millimeter\n")
        proc_file_h.write("*set_model_length_unit millimeter\n")
        proc_file_h.write("|\n")

#==============================================================================
def write_proc_file(dat_file):

#    print("dat_file: ", dat_file)
    proc_file = dat_file + ".proc"
#    print("proc_file: ", proc_file)

    proc_file_h = open(proc_file, 'w')
    write_proc_header(proc_file_h)

    command = '*import marc_read ' + '"' + dat_file + '"' + '\n'
    proc_file_h.write(command)

    proc_file_h.write('*fill_view\n')

    proc_file_h.close()

    return proc_file

#==============================================================================
def main(dict={}):

    apex.disableShowOutput()
    model_1 = apex.currentModel()

    # Dict to transfer settings regarding model specifics, such as settings per contact body, event settings et.c.
    OptionsD={}

    settings_file = dict["xml_file"]
    dat_path      = dict["dat_path"]
    runMentat     = dict["RunMentat"]
    mentat_exe    = dict["MentatPath"]

    #settings_file = file_path + "/res/UtilityUserSettings.xml"
    #settings_file=

    try:
        if os.path.isfile(settings_file):
            pass
        else:
            print("Settings file not selected")
            return
    except:
        print("Something is wrong the settings file: " + settings_file + " doesn't seem to exist")
        return

    try:
        SettingsD=read_settings(settings_file)
    except:
        print("reading of Settings file failed... exit")
        return

    # create a variable that we can later access
    SettingsD['System']['SettingsFile']=settings_file

    if dat_path=="":
        print("***Warning***No export filename given")
        return

    #====Analysis Options ==================

    try:
        export_units=SettingsD['System']['ExportUnitSystem']
    except:
        print("Could not obtain default units from settings file")
        return

    #Not supported set up for Marc yet
    hierarchy_flag=False

    model_1.exportMarc(
        filename = dat_path,
        unitSystem = export_units,
        exportWideFormat = False,
        exportHierarchicalFiles = hierarchy_flag,
        renumberMethod = apex.attribute.ExportRenumberMethod.Internal,
        exportAbstractions = False,
    )

    print("Done exporting")

    if runMentat == "True":
      out_proc_file = write_proc_file(dat_path)

      #mentat_exe = r"C:\Program Files\MSC.Software\Marc\2020.1.0\mentat2020.1\bin\mentat.bat"

      args = []
      args.append(mentat_exe)
      args.append("-pr")
      args.append('"' + out_proc_file + '"')

      print("Mentat executable args:")
      print(args)

      marc_cwd = os.path.dirname(out_proc_file)

      # modify the SCA resource dir env variable, that conflicts the nastran run
      my_env = os.environ
      my_env["SCA_RESOURCE_DIR"] = ""

      stdout_h=open(marc_cwd + "\\stdout.log",'w')
      stderr_h=open(marc_cwd + "\\stderr.log",'w')

      p = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, cwd=marc_cwd, env=my_env)
      out, err = p.communicate()
      p.stderr.close()
      p.stdin.close()

##main()
