from __future__ import annotations

import numpy as np
import scikit_fluorescence.math.datatools


def species_averaged_lifetime(
        fluorescence,
        normalize: bool = True,
        is_lifetime_spectrum: bool = True
) -> float:
    """
    Calculates the species averaged lifetime given a lifetime spectrum

    :param fluorescence: either a inter-leaved lifetime-spectrum (if is_lifetime_spectrum is True) or a
        fluorescence decay (times, fluorescence intensity)
    :param normalize:
    :param is_lifetime_spectrum:
    :return:
    """
    if is_lifetime_spectrum:
        x, t = scikit_fluorescence.math.datatools.interleaved_to_two_columns(fluorescence)
        if normalize:
            x /= x.sum()
        tau_x = np.dot(x, t)
        return float(tau_x)
    else:
        time_axis = fluorescence[0]
        intensity = fluorescence[1]

        dt = (time_axis[1] - time_axis[0])
        i2 = intensity / max(intensity)
        return np.sum(i2) * dt


def fluorescence_averaged_lifetime(
        fluorescence,
        taux: float = None,
        normalize: bool = True,
        is_lifetime_spectrum: bool = True
) -> float:
    """

    :param fluorescence: interleaved lifetime spectrum
    :param taux: float
        The species averaged lifetime. If this value is not provided it is calculated based
        on th lifetime spectrum
    :return:
    """
    if is_lifetime_spectrum:
        taux = species_averaged_lifetime(fluorescence) if taux is None else taux
        x, t = scikit_fluorescence.math.datatools.interleaved_to_two_columns(fluorescence)
        if normalize:
            x /= x.sum()
        tau_f = np.dot(x, t**2) / taux
        return tau_f
    else:
        time_axis = fluorescence[0]
        intensity = fluorescence[1]
        return np.sum(intensity * time_axis) / np.sum(intensity)

