"""
Helper functions used during calculations. Uses numba enhanced functions if available, otherwise numpy based
fallback is imported.
"""
import numpy as np
from .event_data_types import EventDatasetProtocol, append_fields

try:
    from .helpers_numba import merge_frames, extract_walltime, filter_project_x, calculate_derived_properties_focussing
except ImportError:
    from .helpers_fallback import merge_frames, extract_walltime, filter_project_x, calculate_derived_properties_focussing

def add_log_to_pulses(key, dataset: EventDatasetProtocol):
    """
    Add a log value for each pulse to the pulses array.
    """
    pulses = dataset.data.pulses
    log_data = dataset.data.device_logs[key]
    if log_data.time[0]>0:
        logTimeS = np.hstack([[0], log_data.time, [pulses.time[-1]+1]])
        logValues = np.hstack([[log_data.value[0]], log_data.value])
    else:
        logTimeS = np.hstack([log_data.time, [pulses.time[-1]+1]])
        logValues = log_data.value
    pulseLogS = np.zeros(pulses.time.shape[0], dtype=log_data.value.dtype)
    j = 0
    for i, ti in enumerate(pulses.time):
        # find the last current item that was before this pulse
        while ti>=logTimeS[j+1]:
            j += 1
        pulseLogS[i] = logValues[j]
    pulses = append_fields(pulses, [(key, pulseLogS.dtype)])
    pulses[key] = pulseLogS
    dataset.data.pulses = pulses

