#!/usr/bin/env python
# -*- coding: utf-8 -*-

def _add_exception(return_dict, e, cmd):
    import subprocess

    return_dict['success'] = False

#  if isinstance(e, subprocess.CalledProcessError):
#    # Check if simulation terminated, and if so, get the error
#    return_dict['stdout'] = e.output.decode("utf-8")
#    output = return_dict['stdout']
#    for line in output.split('\n'):
#      if 'terminated' in line:
#        # Found terminated string. Cut everything after the '|' character that OpenModelica writes.
#        idx=line.rfind('|')
#        msg=line[idx+1:].strip()
#        # The solver terminated. Add this information to a custom exception message.
#        return_dict['exception'] = f"'{' '.join(cmd)}' caused '{msg}'."
#        pass

    if 'exception' not in return_dict:
        # Did not find 'terminated' in message, handle exception as usual
        return_dict['exception'] = '{}: {}'.format(type(e).__name__, e)


def _run_process(return_dict, cmd, worDir, timeout):
    import subprocess

    output = subprocess.check_output(
        cmd,
        cwd=worDir,
        timeout=timeout,
        stderr=subprocess.STDOUT,
        shell=False)

    return_dict['success'] = True
    if 'stdout' in return_dict:
        return_dict['stdout'] += output.decode("utf-8")
    else:
        return_dict['stdout'] = output.decode("utf-8")
    return


def _simulate(model, timeout):
    import os
    import subprocess

    worDir = r"{{ working_directory }}"
    return_dict = {}

    try:
        cmd = {{cmd}}
        return_dict['cmd'] = ' '.join(cmd)
        output = _run_process(return_dict, cmd, worDir, timeout)

    except Exception as e:
        _add_exception(return_dict, e, cmd)
    return return_dict


def run():
    import os
    import json
    import traceback
    import sys

    timeout = {{time_out}}
    model = "{{ model }}"
    result = {"model": model,
              "working_directory": r"{{ working_directory }}",
              "simulation": {"success": False}}

    # Log file
    log_file = "{}_buildingspy.json".format(model.replace(".", "_"))
    try:
        os.remove(log_file)
    except OSError:
        pass

    # Simulate model
    result["simulation"] = _simulate(model, timeout)

    with open(log_file, "w") as log:
        log.write("{}\n".format(json.dumps(result, indent=4, sort_keys=False)))


if __name__ == "__main__":
    run()
