import csv
import datetime
import sys
import time
from pathlib import Path

from PySide6.QtCore import QObject, Signal, QTimer

from .bms import BMSData


class Logger(QObject):
    _data: BMSData
    _current: float
    _log_path: Path
    _start_time: float

    _timer: QTimer

    def __init__(self, bmsUpdated: Signal, currentUpdated: Signal):
        super().__init__(None)

        self._data = None
        self._current = None

        log_dir = Path(__file__).parent / ".." / "logs"
        if not log_dir.is_dir():
            log_dir.mkdir()
        self._log_path = log_dir / datetime.datetime.now().strftime(
            "%Y-%m-%d_%H-%M-%S.csv"
        )
        print(f"Logging to {self._log_path}")
        self._start_time = time.time()

        bmsUpdated.connect(self._updateBMS)
        currentUpdated.connect(self._updateCurrent)

        self._timer = QTimer()
        self._timer.timeout.connect(self._log_data)
        self._timer.start(500)

    def _log_data(self):
        if self._data is None or self._current is None:
            print("WARNING: no data to log", file=sys.stderr)
            return

        with open(self._log_path, "a") as fh:
            writer = csv.writer(fh)
            writer.writerow(
                [
                    time.time() - self._start_time,
                    self._data.error.value,
                    self._current,
                    self._data.current,
                    self._data.current_integrated,
                    *self._data.voltages,
                    *self._data.temperatures,
                ]
            )

    def _updateBMS(self, data: BMSData):
        self._data = data

    def _updateCurrent(self, current: float):
        self._current = current
