from pathlib import Path
import logging
import pyxdf

from .recording import Recording
from .RecordingMetadata import RecordingMetadata
from .errors import BreesyError, BreesyInternalError
from .load import _leave_only_eeg_channels
from .type_hints import enforce_type_hints


@enforce_type_hints
def load_xdf(filename: str) -> Recording:
    pyxdf.pyxdf.logger.setLevel(logging.ERROR)
    streams, _ = pyxdf.load_xdf(filename, verbose=None)
    stream_types = [x['info']['type'] for x in streams]
    eeg_streams_ix = [i for i, x in enumerate(stream_types) if x[0] == "EEG"]  # TODO: can there be more than one in a single stream? Check all [0]
    if len(eeg_streams_ix) > 1:
        raise BreesyError("Found more than one EEG stream in file.", "Currently, Breesy does not support multiple EEG streams in single .xdf file, sorry :(")
    eeg_stream = streams[eeg_streams_ix[0]]

    channel_count = int(eeg_stream['info']['channel_count'][0])
    sample_rate = int(eeg_stream['info']['nominal_srate'][0])
    channel_names = [row['label'][0] for row in eeg_stream['info']['desc'][0]['channels'][0]['channel']]
    if len(channel_names) != channel_count:
        raise BreesyInternalError("Number of channels does not correspond to number of extracted channel names.")
    data_array = eeg_stream['time_series'].T
    data_array, channel_names = _leave_only_eeg_channels(data_array, channel_names)

    metadata = RecordingMetadata(
        name=Path(filename).stem,
        file_path=Path(filename),
        description=f"XDF data loaded from {filename}"
    )

    return Recording(
        data=data_array,
        channel_names=channel_names,
        sample_rate=sample_rate,
        metadata=metadata
    )
