from .Core import Experiment


def read(filename_input, wanted_ms_level=None):
    from pymzml import run
    experiment = Experiment.Experiment()
    ms_run = run.Reader(filename_input)

    for spectrum in ms_run:
        retention_time = spectrum.scan_time[0]
        if spectrum.scan_time[1] == 'minute':
            retention_time *= 60
        if spectrum.ms_level == 1 and \
                ((wanted_ms_level is None) or (wanted_ms_level is not None and 1 in wanted_ms_level)):
            experiment.add_ms1(
                spectrum_data=spectrum.centroidedPeaks.T,
                scan_num=int(spectrum.ID),
                retention_time=float(retention_time)
            )
            pass

        elif spectrum.ms_level == 2 and \
                ((wanted_ms_level is None) or (wanted_ms_level is not None and 2 in wanted_ms_level)):
            precursor_charge = spectrum.selected_precursors[0]['charge']
            experiment.add_ms2(spectrum_data=spectrum.centroidedPeaks.T,
                               precursor_mz=float(spectrum.selected_precursors[0]['mz']),
                               precursor_charge=precursor_charge,
                               scan_num=int(spectrum.ID),
                               retention_time=float(retention_time))

    return experiment
