import serial
import time

from PySide6.QtCore import QObject, Slot, QTimer

from .profile_handler import ProfileHandler


class Load(QObject):
    dev: serial.Serial

    _error: bool
    _current: float

    _timer: QTimer
    _profile_handler: ProfileHandler

    def __init__(self, uart_path: str, profile_handler: ProfileHandler):
        super().__init__(None)
        self.dev = serial.Serial(uart_path, 115200)
        self._error = False
        self._current = 0

        self._profile_handler = profile_handler
        self._profile_handler.currentChanged.connect(self._update_current)
        self._timer = QTimer()
        self._timer.timeout.connect(self._update_load)
        self._timer.start(100)

    def set_error(self, error):
        self._error = error

    @Slot()
    def _update_current(self, current):
        self._current = current

    def _update_load(self):
        current = 0 if self._error else self._current
        curr_quants = round(current / 0.1)
        assert curr_quants <= 0xFFFF

        msb = curr_quants >> 8
        lsb = curr_quants & 0xFF
        self.dev.write(bytes((msb, lsb)))
        r = self.dev.read_all()
        read_bytes = 0 if r is None else len(r)
        print(f"Read {read_bytes} bytes from load controller")
