"""
Interface between loop object and ebtel++ simulation
"""

import os
import logging
import copy

import numpy as np
import astropy.units as u

from synthesizAR.util import InputHandler,OutputHandler


class EbtelInterface(object):
    """
    Interface between field/loop model for the EBTEL model

    Parameters
    ----------
    base_config : `dict`
        Config dictionary with default parameters for all loops.
    heating_model
    """

    def __init__(self,base_config,heating_model):
        """
        Create EBTEL interface
        """
        self.logger = logging.getLogger(name=type(self).__name__)
        self.base_config = base_config
        self.heating_model = heating_model
        self.heating_model.base_config = base_config


    def configure_input(self,loop,parent_config_dir,parent_results_dir):
        """
        Configure EBTEL input for a given loop object.

        Parameters
        ----------
        loop
        parent_config_dir : `string`
        parent_results_dir : `string`
        """
        oh = OutputHandler(os.path.join(parent_config_dir,loop.name+'.xml'), copy.deepcopy(self.base_config))
        oh.output_dict['output_filename'] = os.path.join(parent_results_dir,loop.name)
        oh.output_dict['loop_length'] = loop.full_length.value/2.0
        event_properties = self.heating_model.calculate_event_properties(loop)
        events = []
        for i in range(self.heating_model.number_events):
            events.append({'event':{
            'magnitude':event_properties['magnitude'][i], 'rise_start':event_properties['rise_start'][i], 'rise_end':event_properties['rise_end'][i], 'decay_start':event_properties['decay_start'][i], 'decay_end':event_properties['decay_end'][i]}})
        oh.output_dict['heating']['events'] = events
        oh.print_to_xml()
        oh.output_dict['config_filename'] = oh.output_filename
        loop.hydro_configuration = oh.output_dict


    def load_results(self,loop):
        """
        Load EBTEL output for a given loop object.

        Parameters
        ----------
        loop
        """
        N_s = len(loop.field_aligned_coordinate)
        _tmp = np.loadtxt(loop.hydro_configuration['output_filename'])
        loop.time = _tmp[:,0]*u.s
        loop.temperature = np.outer(_tmp[:,1],np.ones(N_s))*u.K
        loop.density = np.outer(_tmp[:,3],np.ones(N_s))*(u.cm**(-3))

@@ -112,16 +112,60 @@
 y as np%0A
+from scipy.interpolate import splprep,splev%0A
 import a
@@ -533,16 +533,31 @@
 ng_model
+,dt=1.0,ds=None
 ):%0A     
@@ -807,16 +807,345 @@
 _config%0A
+        self.global_time = np.linspace(0.0,self.base_config%5B'total_time'%5D,%0A                int(np.ceil(self.base_config%5B'total_time'%5D/dt)))*u.s%0A        self.ds = ds%0A        if self.ds is None:%0A            self.logger.warning('Interpolated loop spacing set to None. You will not be able to load loop results until this is set.')%0A%0A
 %0A%0A    de
@@ -2465,35 +2465,473 @@
    loop%0A        
-%22%22%22
+dt%0A        ds%0A        %22%22%22%0A        #interpolate loop lengths to higher resolution with a B-spline%0A        N_interp = int(np.ceil(loop.full_length/self.ds.to(loop.full_length.unit)))%0A        nots,_ = splprep(loop.coordinates.value.T)%0A        _tmp = splev(np.linspace(0,1,N_interp),nots)%0A        loop.coordinates = %5B(x,y,z) for x,y,z in zip(_tmp%5B0%5D,_tmp%5B1%5D,_tmp%5B2%5D)%5D*loop.coordinates.unit%0A        #load in data and interpolate to universal time
 %0A        N_s = l
@@ -3053,64 +3053,69 @@
 op.t
-ime = _tmp%5B:,0%5D*u.s%0A        loop.temperature = np.outer(
+emperature = np.outer(np.interp(self.global_time, _tmp%5B:,0%5D, 
 _tmp
@@ -3119,17 +3119,19 @@
 tmp%5B:,1%5D
-,
+), 
 np.ones(
@@ -3172,16 +3172,55 @@
 p.outer(
+np.interp(self.global_time, _tmp%5B:,0%5D, 
 _tmp%5B:,3
@@ -3220,17 +3220,19 @@
 tmp%5B:,3%5D
-,
+), 
 np.ones(

interpolate loop coordinates to desired resolution and interpolate time to global time for all loops