"""
The :py:mod:`run_energyplan` module is a wrapper function to run
the EnergyPLAN model.
"""

import subprocess as sp
import os


def create_new_input_file(input_file, new_input_file, x):
    """

    This function writes a new input file for the EnergyPLAN model.
    The new input file copies the lines from the original input file,
    but replaces the default values related to the model parameters
    with the new values generated by the UQ or optimization algorithm.

    Parameters
    ----------
    input_file : str
        The path of the default input file.
    new_input_file : str
        The path of the new input file.
    x : dict
        The new values for the model parameters.

    """

    with open(input_file, 'r') as f:
        lines = f.readlines()

    skip_line = False
    with open(new_input_file, 'w') as f:
        for line in lines:
            if not skip_line:
                if str(line) == 'Input_el_demand_Twh=\n':
                    f.write(line)
                    f.write(str(x['elec_demand']) + '\n')
                    skip_line = True
                elif str(line) == 'input_eff_hp2_cop=\n':
                    f.write(line)
                    f.write(str(x['COP']) + '\n')
                    skip_line = True
                elif str(line) == 'input_eff_ELTtrans_fuel=\n':
                    f.write(line)
                    f.write(str(x['eff_H2']) + '\n')
                    skip_line = True
                elif str(line) == 'input_eff_chp2_el=\n':
                    f.write(line)
                    f.write(str(x['CHP_eff_el']) + '\n')
                    skip_line = True
                elif str(line) == 'input_eff_chp3_el=\n':
                    f.write(line)
                    f.write(str(x['CHP_eff_el']) + '\n')
                    skip_line = True
                elif str(line) == 'input_eff_chp2_th=\n':
                    f.write(line)
                    f.write(str(x['CHP_eff_th']) + '\n')
                    skip_line = True
                elif str(line) == 'input_eff_chp3_th=\n':
                    f.write(line)
                    f.write(str(x['CHP_eff_th']) + '\n')
                    skip_line = True
                else:
                    f.write(line)
            else:
                skip_line = False


def read_output_file(result_file):
    """

    This function reads the output file, generated by
    the EnergyPLAN model. From this output file, the
    values for the CO2-emission and fuel consumption
    are stored and returned.

    Parameters
    ----------
    result_file : str
        Path of the result file.

    Returns
    -------
    co2 : float
        The CO2-emission returned by the EnergyPLAN model.
    fuel : float
        The fuel consumption returned by the EnergyPLAN model.

    """
    with open(result_file, 'r') as f:
        lines = f.readlines()

    co2_str = ''
    fuel_str = ''
    for line in lines:
        if 'CO2-emission (total)' in line:
            for j in line[40:46]:
                if j == ',':
                    j = '.'
                co2_str += j
                co2 = float(co2_str)
        if 'Fuel Consumption (total)' in line:
            for j in line[40:46]:
                if j == ',':
                    j = '.'
                fuel_str += j
                fuel = float(fuel_str)

    return co2, fuel


def energyplan(x_tup):
    """

    This function generates a new input file, evaluates
    this input file in the EnergyPLAN model and reads
    the values for the quantities of interest from the
    generated output file. These values are returned.

    Parameters
    ----------
    x_tup : tuple
        The input sample with index that corresponds to
        the position of the sample in the list of samples.

    Returns
    -------
    co2 : float
        The CO2-emission returned by the EnergyPLAN model.
    fuel : float
        The fuel consumption returned by the EnergyPLAN model.

    """

    x = x_tup[1]
    index = x_tup[0]
    path = os.path.dirname(os.path.abspath(__file__))

    ep_path = r'C:\energyPLAN\energyPLAN.exe'
    input_file = os.path.join(path, 'case.txt')

    new_input_file = '%s_%i.txt' % (input_file[:-4], index)

    # create a new input file for evaluation in EnergyPLAN
    create_new_input_file(input_file, new_input_file, x)

    result_file = os.path.join(path, 'result_%i.txt' % index)

    # evaluate the EnergyPLAN model
    cm = [ep_path, '-i', new_input_file, '-ascii', result_file]
    sp.call(cm)

    # read the output file, generated by the EnergyPLAN model
    co2, fuel = read_output_file(result_file)

    os.remove(result_file)
    os.remove(new_input_file)

    return co2, fuel
