# Path: tellurium/temiriam.py
# def getSBMLFromBiomodelsURN(urn):
# 
# Path: tellurium/sedml/tesedml.py
# def executeCombineArchive(omexPath,
#                           workingDir=None,
#                           printPython=False,
#                           createOutputs=True,
#                           saveOutputs=False,
#                           outputDir=None,
#                           plottingEngine=None):
#     """ Run all SED-ML simulations in given COMBINE archive.
# 
#     If no workingDir is provided execution is performed in temporary directory
#     which is cleaned afterwards.
#     The executed code can be printed via the 'printPython' flag.
# 
#     :param omexPath: OMEX Combine archive
#     :param workingDir: directory to extract archive to
#     :param printPython: boolean switch to print executed python code
#     :param createOutputs: boolean flag if outputs should be created, i.e. reports and plots
#     :param saveOutputs: flag if the outputs should be saved to file
#     :param outputDir: directory where the outputs should be written
#     :param plottingEngin: string of which plotting engine to use; uses set plotting engine otherwise
#     :return dictionary of sedmlFile:data generators
#     """
# 
#     # combine archives are zip format
#     if zipfile.is_zipfile(omexPath):
#         try:
#             tmp_dir = tempfile.mkdtemp()
#             if workingDir is None:
#                 extractDir = tmp_dir
#             else:
#                 if not os.path.exists(workingDir):
#                     raise IOError("workingDir does not exist, make sure to create the directoy: '{}'".format(workingDir))
#                 extractDir = workingDir
# 
#             # extract
#             omex.extractCombineArchive(omexPath=omexPath, directory=extractDir)
# 
#             # get sedml locations by omex
#             sedml_locations = omex.getLocationsByFormat(omexPath=omexPath, formatKey="sed-ml", method="omex")
#             if len(sedml_locations) == 0:
# 
#                 # falling back to zip archive
#                 sedml_locations = omex.getLocationsByFormat(omexPath=omexPath, formatKey="sed-ml", method="zip")
#                 warnings.warn(
#                     "No SED-ML files in COMBINE archive based on manifest '{}'; Guessed SED-ML {}".format(omexPath, sedml_locations))
# 
# 
#             # run all sedml files
#             results = {}
#             sedml_paths = [os.path.join(extractDir, loc) for loc in sedml_locations]
#             for sedmlFile in sedml_paths:
#                 factory = SEDMLCodeFactory(sedmlFile,
#                                            workingDir=os.path.dirname(sedmlFile),
#                                            createOutputs=createOutputs,
#                                            saveOutputs=saveOutputs,
#                                            outputDir=outputDir,
#                                            plottingEngine=plottingEngine
#                                            )
#                 if printPython:
#                     code = factory.toPython()
#                     print(code)
# 
#                 results[sedmlFile] = factory.executePython()
# 
#             return results
#         finally:
#             shutil.rmtree(tmp_dir)
#     else:
#         if not os.path.exists(omexPath):
#             raise FileNotFoundError("File does not exist: {}".format(omexPath))
#         else:
#             raise IOError("File is not an OMEX Combine Archive in zip format: {}".format(omexPath))
# 
# def executeSEDML(inputStr, workingDir=None):
#     """ Run a SED-ML file or combine archive with results.
# 
#     If a workingDir is provided the files and results are written in the workingDir.
# 
#     :param inputStr:
#     :type inputStr:
#     :return:
#     :rtype:
#     """
#     # execute the sedml
#     factory = SEDMLCodeFactory(inputStr, workingDir=workingDir)
#     factory.executePython()
# 
# Path: tellurium/utils/omex.py
# MANIFEST_PATTERN = "manifest.xml"
# METADAT_PATTERN = "metadata.*"
# class Entry(object):
# class Creator(object):
#     def __init__(self, location, format=None, formatKey=None, master=False, description=None, creators=None):
#     def __str__(self):
#     def __init__(self, givenName, familyName, organization, email):
# def combineArchiveFromDirectory(directory, omexPath, creators=None, creators_for_all=False):
# def combineArchiveFromEntries(omexPath, entries, workingDir):
# def addEntriesToCombineArchive(omexPath, entries, workingDir):
# def _addEntriesToArchive(omexPath, entries, workingDir, add_entries):
# def extractCombineArchive(omexPath, directory, method="zip"):
# def getLocationsByFormat(omexPath, formatKey=None, method="omex"):
# def listContents(omexPath, method="omex"):
# def printContents(omexPath):


import os
import tempfile
import shutil
import phrasedml
from tellurium import temiriam
from tellurium.sedml.tesedml import executeCombineArchive, executeSEDML
from tellurium.utils import omex
                                                       task1.PY/max(task1.PY) vs task1.PX/max(task1.PX), \
                                                       task1.PZ/max(task1.PZ) vs task1.PY/max(task1.PY)
""".format(urn)

# convert to sedml
sedml_str = phrasedml.convertString(phrasedml_str)
if sedml_str is None:
    print(phrasedml.getLastError())
    raise IOError("sedml could not be generated")

# run SEDML directly
try:
    tmp_dir = tempfile.mkdtemp()
    executeSEDML(sedml_str, workingDir=tmp_dir)
finally:
    shutil.rmtree(tmp_dir)


# create combine archive and execute
try:
    tmp_dir = tempfile.mkdtemp()
    sedml_location = "repressilator_sedml.xml"
    sedml_path = os.path.join(tmp_dir, sedml_location)
    omex_path = os.path.join(tmp_dir, "repressilator.omex")
    with open(sedml_path, "w") as f:
        f.write(sedml_str)

    entries = [
        omex.Entry(location=sedml_location, formatKey="sedml", master=True)
    ]

# Path: tellurium/temiriam.py
# def getSBMLFromBiomodelsURN(urn):
# 
# Path: tellurium/sedml/tesedml.py
# def executeCombineArchive(omexPath,
#                           workingDir=None,
#                           printPython=False,
#                           createOutputs=True,
#                           saveOutputs=False,
#                           outputDir=None,
#                           plottingEngine=None):
#     """ Run all SED-ML simulations in given COMBINE archive.
# 
#     If no workingDir is provided execution is performed in temporary directory
#     which is cleaned afterwards.
#     The executed code can be printed via the 'printPython' flag.
# 
#     :param omexPath: OMEX Combine archive
#     :param workingDir: directory to extract archive to
#     :param printPython: boolean switch to print executed python code
#     :param createOutputs: boolean flag if outputs should be created, i.e. reports and plots
#     :param saveOutputs: flag if the outputs should be saved to file
#     :param outputDir: directory where the outputs should be written
#     :param plottingEngin: string of which plotting engine to use; uses set plotting engine otherwise
#     :return dictionary of sedmlFile:data generators
#     """
# 
#     # combine archives are zip format
#     if zipfile.is_zipfile(omexPath):
#         try:
#             tmp_dir = tempfile.mkdtemp()
#             if workingDir is None:
#                 extractDir = tmp_dir
#             else:
#                 if not os.path.exists(workingDir):
#                     raise IOError("workingDir does not exist, make sure to create the directoy: '{}'".format(workingDir))
#                 extractDir = workingDir
# 
#             # extract
#             omex.extractCombineArchive(omexPath=omexPath, directory=extractDir)
# 
#             # get sedml locations by omex
#             sedml_locations = omex.getLocationsByFormat(omexPath=omexPath, formatKey="sed-ml", method="omex")
#             if len(sedml_locations) == 0:
# 
#                 # falling back to zip archive
#                 sedml_locations = omex.getLocationsByFormat(omexPath=omexPath, formatKey="sed-ml", method="zip")
#                 warnings.warn(
#                     "No SED-ML files in COMBINE archive based on manifest '{}'; Guessed SED-ML {}".format(omexPath, sedml_locations))
# 
# 
#             # run all sedml files
#             results = {}
#             sedml_paths = [os.path.join(extractDir, loc) for loc in sedml_locations]
#             for sedmlFile in sedml_paths:
#                 factory = SEDMLCodeFactory(sedmlFile,
#                                            workingDir=os.path.dirname(sedmlFile),
#                                            createOutputs=createOutputs,
#                                            saveOutputs=saveOutputs,
#                                            outputDir=outputDir,
#                                            plottingEngine=plottingEngine
#                                            )
#                 if printPython:
#                     code = factory.toPython()
#                     print(code)
# 
#                 results[sedmlFile] = factory.executePython()
# 
#             return results
#         finally:
#             shutil.rmtree(tmp_dir)
#     else:
#         if not os.path.exists(omexPath):
#             raise FileNotFoundError("File does not exist: {}".format(omexPath))
#         else:
#             raise IOError("File is not an OMEX Combine Archive in zip format: {}".format(omexPath))
# 
# def executeSEDML(inputStr, workingDir=None):
#     """ Run a SED-ML file or combine archive with results.
# 
#     If a workingDir is provided the files and results are written in the workingDir.
# 
#     :param inputStr:
#     :type inputStr:
#     :return:
#     :rtype:
#     """
#     # execute the sedml
#     factory = SEDMLCodeFactory(inputStr, workingDir=workingDir)
#     factory.executePython()
# 
# Path: tellurium/utils/omex.py
# MANIFEST_PATTERN = "manifest.xml"
# METADAT_PATTERN = "metadata.*"
# class Entry(object):
# class Creator(object):
#     def __init__(self, location, format=None, formatKey=None, master=False, description=None, creators=None):
#     def __str__(self):
#     def __init__(self, givenName, familyName, organization, email):
# def combineArchiveFromDirectory(directory, omexPath, creators=None, creators_for_all=False):
# def combineArchiveFromEntries(omexPath, entries, workingDir):
# def addEntriesToCombineArchive(omexPath, entries, workingDir):
# def _addEntriesToArchive(omexPath, entries, workingDir, add_entries):
# def extractCombineArchive(omexPath, directory, method="zip"):
# def getLocationsByFormat(omexPath, formatKey=None, method="omex"):
# def listContents(omexPath, method="omex"):
# def printContents(omexPath):


# Path: examples/tellurium-files/phrasedml/repressilator.py
import os
import tempfile
import shutil
import phrasedml
from tellurium import temiriam
from tellurium.sedml.tesedml import executeCombineArchive, executeSEDML
from tellurium.utils import omex

                                                       task1.PY/max(task1.PY) vs task1.PX/max(task1.PX), \
                                                       task1.PZ/max(task1.PZ) vs task1.PY/max(task1.PY)
""".format(urn)

# convert to sedml
sedml_str = phrasedml.convertString(phrasedml_str)
if sedml_str is None:
    print(phrasedml.getLastError())
    raise IOError("sedml could not be generated")

# run SEDML directly
try:
    tmp_dir = tempfile.mkdtemp()
    executeSEDML(sedml_str, workingDir=tmp_dir)
finally:
    shutil.rmtree(tmp_dir)


# create combine archive and execute
try:
    tmp_dir = tempfile.mkdtemp()
    sedml_location = "repressilator_sedml.xml"
    sedml_path = os.path.join(tmp_dir, sedml_location)
    omex_path = os.path.join(tmp_dir, "repressilator.omex")
    with open(sedml_path, "w") as f:
        f.write(sedml_str)

    entries = [
        omex.Entry(location=sedml_location, formatKey="sedml", master=True)
    ]

    omex.combineArchiveFromEntries(omexPath=omex_path, entries=entries, workingDir=tmp_dir)