import jinja2


def create_main_protocol_hoc(
    template_path, protocol_definitions, rin_exp_voltage_base, mtype
):
    """Create main_protocol.hoc file.

    Args:
        template_path (str): path to the template to fill in
        protocol_definitions (dict): dictionary defining the protocols
        rin_exp_voltage_base (float): experimental value
            for the voltage_base feature for Rin protocol
        mtype (str): mtype of the cell. prefix to use in the output files names

    Returns:
        str: hoc script containing the main protocol functions
    """
    with open(template_path, "r", encoding="utf-8") as template_file:
        template = template_file.read()
        template = jinja2.Template(template)

    rmp_stim = protocol_definitions["RMP"]["stimuli"]
    rin_stim = protocol_definitions["Rin"]["stimuli"]
    thresh_stim = protocol_definitions["ThresholdDetection"]["step_template"]["stimuli"]

    # edit template
    return template.render(
        rmp_stimulus_dur=rmp_stim["step"]["duration"],
        rmp_stimulus_del=rmp_stim["step"]["delay"],
        rmp_stimulus_amp=rmp_stim["step"]["amp"],
        rmp_stimulus_totduration=rmp_stim["step"]["totduration"],
        rmp_output_path=f"hoc_recordings/{mtype}.RMP.soma.v.dat",
        rin_stimulus_dur=rin_stim["step"]["duration"],
        rin_stimulus_del=rin_stim["step"]["delay"],
        rin_stimulus_amp=rin_stim["step"]["amp"],
        rin_stimulus_totduration=rin_stim["step"]["totduration"],
        rin_holding_dur=rin_stim["holding"]["duration"],
        rin_holding_del=rin_stim["holding"]["delay"],
        holdi_precision=protocol_definitions["RinHoldcurrent"]["holdi_precision"],
        holdi_max_depth=protocol_definitions["RinHoldcurrent"]["holdi_max_depth"],
        voltagebase_exp_mean=rin_exp_voltage_base,
        rin_output_path=f"hoc_recordings/{mtype}.Rin.soma.v.dat",
        holding_current_output_path=f"hoc_recordings/{mtype}.bpo_holding_current.dat",
        thdetect_stimulus_del=thresh_stim["step"]["delay"],
        thdetect_stimulus_dur=thresh_stim["step"]["duration"],
        thdetect_stimulus_totduration=thresh_stim["step"]["totduration"],
        thdetect_holding_dur=thresh_stim["holding"]["duration"],
        thdetect_holding_del=thresh_stim["holding"]["delay"],
        threshold_current_output_path=f"hoc_recordings/{mtype}.bpo_threshold_current.dat",
    )