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

from pathlib import Path

from PyQt6.QtCore import QObject, pyqtSignal, pyqtSlot

from pymagnetos.linx import LinxProcessor


class DataWorker(QObject):
    """
    Wrapper around the LinxProcessor class.

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

    sig_load_data_finished = pyqtSignal()
    sig_compute_field_finished = pyqtSignal()
    sig_demodulate_finished = pyqtSignal()
    sig_export_csv_finished = pyqtSignal()
    sig_save_nexus_finished = pyqtSignal()

    sig_align_finished = pyqtSignal()  # required by core
    sig_batch_finished = pyqtSignal()  # required by core

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

        self.proc = LinxProcessor(*args, **kwargs)
        if self.proc.is_nexus_file:
            self.is_data_loaded = True
        else:
            self.is_data_loaded = False

    @pyqtSlot()
    def load_data(self) -> None:
        """Load data."""
        self.proc.load_oscillo()
        self.is_data_loaded = True
        self.proc.demodulate().compute_resistance()
        self.sig_load_data_finished.emit()

    @pyqtSlot()
    def compute_field(self) -> None:
        """Compute field."""
        self.proc.compute_field()
        self.sig_compute_field_finished.emit()

    @pyqtSlot()
    def find_f0(self) -> None:
        """Find reference center frequency."""
        self.proc.find_f0()
        self.run_analysis()

    @pyqtSlot()
    def auto_phase(self) -> None:
        """Find the phase offset that maximizes the in-phase signal."""
        self.proc.find_phase_offset()
        self.run_analysis()

    @pyqtSlot()
    def run_analysis(self) -> None:
        """Run the digital demodulation."""
        self.proc.run_analysis()
        self.sig_demodulate_finished.emit()

    @pyqtSlot(str, int, bool)
    def export_csv(self, fname: str | Path, downsample: int, average: bool) -> None:
        """Export demodulated signal as CSV."""
        self.proc.to_csv(fname, downsample=downsample, average=average)
        self.sig_export_csv_finished.emit()

    @pyqtSlot(str)
    def save_as_nexus(self, fname: str | Path) -> None:
        """Save data as NeXus."""
        self.proc.save(filename=fname)
        self.sig_save_nexus_finished.emit()

    @pyqtSlot()
    def batch_process(self) -> None:
        """Required by core."""
        pass
