try:
    import pysp2

    PYSP2_AVAILABLE = True
except ImportError:
    PYSP2_AVAILABLE = False


def calc_sp2_diams_masses(input_ds, debug=True, factor=1.0, Globals=None):
    """
    Calculates the scattering and incandescence diameters/BC masses for each particle.

    Parameters
    ----------
    input_ds: ACT Dataset
        The ACT Dataset containing the processed SP2 data.
    debug: boolean
        If true, print out particle rejection statistics
    factor: float
        Multiply soot masses by this factor for AquaDag calibation. Use
        1.3 for NSA.
    Globals: act.qc.SP2ParticleCriteria structure or None
        DMTGlobals structure containing calibration coefficients. Set to
        None to use default values for MOSAiC.

    Returns
    -------
    output_ds: ACT Dataset
        The ACT Dataset containing the scattering/incadescence diameters.
    """
    if PYSP2_AVAILABLE:
        return pysp2.util.calc_diams_masses(input_ds, debug, factor, Globals)
    else:
        raise ModuleNotFoundError('PySP2 needs to be installed to use this feature.')


def process_sp2_psds(
    particle_ds, hk_ds, config_file, deltaSize=0.005, num_bins=199, avg_interval=10
):
    """
    Processes the Scattering and BC mass size distributions:

    Parameters
    ----------
    particle_ds: xarrray Dataset
        The xarray Dataset containing the particle statistics generated by
        act.retrievals.calc_sp2_diams_masses.
    hk_ds: xarray Dataset
        The xarray Dataset containing the housekeeping variables
    config_file: file_name
        Path to the .INI file.
    deltaSize: float
        The size distribution bin width in microns.
    num_bins: int
        The number of size bins
    avg_interval: int
        The time in seconds to average the concentrations into.

    Returns
    -------
    psd_ds: xarray Dataset
        The xarray Dataset containing the time-averaged particle statistics.
    """
    if PYSP2_AVAILABLE:
        config = pysp2.io.read_config(config_file)
        return pysp2.util.process_psds(
            particle_ds, hk_ds, config, deltaSize, num_bins, avg_interval
        )
    else:
        raise ModuleNotFoundError('PySP2 needs to be installed to use this feature.')
