# This script is for simulation using JModelica.org
from pymodelica import compile_fmu
from pyfmi import load_fmu

print 'Loaded python packages from JModelica.'
# Compile .mo file to fmu executable
print 'Compiling Modelica model...'
fmu_name = compile_fmu('<%-modelName%>', '<%-modelName%>.mo')
print 'Compilation done!'

# Load the compiled fmu
print 'Loading in compiled model...'
model = load_fmu(fmu_name)
print 'Compiled model loaded!'

# Simulate the model
print 'Simulating model (this may take a while)...'
res = model.simulate(final_time=<%-stopTime%>)

res_info = {
    'info': {
        'name': '<%-modelName%>',
        'description': ''
    },
    'variables': {},
    'timeSeries': {}
}

csv_lines = [[] for x in xrange(len(res['time']) + 1)]

for v_name in res.result_data.name:
    if res.result_data.is_variable(v_name):
        # FIXME: res.result_data.description(v_name) throws exception..
        # What is the correct way of getting description?
        res_info['variables'][v_name] = {
            'comment': '',
            'kind': 'variable',
            'type': '',
            'unit': '',
            'displayUnit': ''
        }
        res_info['timeSeries'][v_name] = res[v_name].tolist()

        csv_lines[0].append(v_name)
        cnt = 1
        for t_val in res[v_name]:
            csv_lines[cnt].append(repr(t_val))
            cnt += 1

import json
with open('<%-modelName%>_res.json', 'w') as outfile:
    json.dump(res_info, outfile)

with open('<%-modelName%>_res.csv', 'w') as outfile:
    for csv_line in csv_lines:
        outfile.write(','.join(csv_line) + '\n')
