"""Worker that connects to an EchoProcessor object."""

from PyQt6.QtCore import pyqtSignal as Signal
from PyQt6.QtCore import pyqtSlot as Slot

from pymagnetos.core.gui import BaseWorker
from pymagnetos.pyuson import EchoProcessor


class Worker(BaseWorker):
    """
    Wrapper around the EchoProcessor object.

    It exposes the EchoProcessor methods as slots and emits a signal when the task is
    finished.

    Additional signals
    ------------------
    sig_rolling_finished : emits when rolling average is finished.
    sig_find_f0_finished : emits f0 (float) when the center frequency is found.
    sig_export_csv_finished : emits when the results are exported to CSV.
    """

    proc: EchoProcessor
    _type_processor: type[EchoProcessor] = EchoProcessor

    sig_rolling_finished: Signal = Signal()
    sig_find_f0_finished: Signal = Signal(float)
    sig_export_csv_finished: Signal = Signal()

    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

        # Setup methods arguments
        self._after_load_align = True
        self._kwargs_load = {"scale": True}
        self._kwargs_preprocess = {"progress_emitter": self.sig_preprocess_progress}
        self._kwargs_analysis = {}

    @Slot()
    def rolling_average(self) -> None:
        """Apply moving average."""
        self.proc.rolling_average()
        self.sig_rolling_finished.emit()

    @Slot()
    def find_f0(self) -> None:
        """Find F0."""
        self.proc.find_f0()
        self.sig_find_f0_finished.emit(self.proc.cfg.demodulation.f0)

    @Slot(tuple)
    def batch_process(
        self,
        args: tuple,
    ) -> None:
        """Batch-process several datasets."""
        self.proc.batch_process(
            *args,
            demodulation_progress_emitter=self.sig_preprocess_progress,
            batch_progress_emitter=self.sig_batch_progress,
        )

        # Emit signals
        self.sig_load_data_finished.emit()
        if self.proc.is_digital:
            self.sig_preprocess_finished.emit()
        self.sig_analysis_finished.emit()
        self.sig_batch_finished.emit()

    @Slot(str, bool)
    def export_as_csv(self, fname: str, to_cm: bool) -> None:
        """Export results as CSV."""
        self.proc.export_csv(fname=fname, to_cm=to_cm)
        self.sig_export_csv_finished.emit()
