import subprocess
from lxml import etree as et
import sys
import os


def run_all_in_file(xml_file, febioCommand = None):
    """ use the exp_to_model.xml file to get a list of models to run and run them"""

    if not febioCommand:
        febioCommand = '/home/schwara2/Programs/FEBio/FEBio2.8.2/bin/febio2.lnx64'
        print('Using {} to call febio'.format(febioCommand))

    file_tree = et.parse(xml_file)
    file_info = file_tree.getroot()

    gen_files = file_info.find("general_files")
    feb_file = gen_files.find("febio_file").text

    dirname = os.path.dirname(feb_file)

    models = file_info.find("Models")

    # collect the names of all the models to run

    all_model_files = []
    for mod in models:
        if mod.tag is et.Comment:
            continue

        model_name = mod.attrib["name"]
        model_file = model_name+'.feb'
        all_model_files.append(model_file)

    # go to the the directory containing the files
    # (need to run from here, or specify the full file path for the geometry file)
    os.chdir(dirname)

    # run the models
    for mf in all_model_files:
        subprocess.call([febioCommand, mf])

if __name__ == '__main__':

    run_all_in_file(*sys.argv[1:])