from PyQt5.QtCore import pyqtSignal

from .component import Component


class TecnaScrewdriver(Component):
    request = pyqtSignal(object)

    def __init__(self, config=None, name=None, period=None, lazy=True, paused=False, threaded=True):
        super().__init__(config=config, name=name, period=period, lazy=lazy, paused=paused, threaded=threaded)
        self.enabled = False
        self.last_screwed = False

    def config_changed(self):
        super().config_changed()
        self.disable_pin = int(self.config[self.name]["disable_pin"])
        self.status_pin = int(self.config[self.name]["status_pin"])
        self.status_pin_mask = 1 << self.status_pin

    @Component.reconfig_on_error
    def enable(self, enabled=True):
        self.enabled = enabled
        if self.enabled:
            self.request.emit({"Reset specific digital output": self.disable_pin})
        else:
            self.request.emit({"Activate specific digital output": self.disable_pin})

    @Component.reconfig_on_error
    def disable(self, disabled=True):
        self.enable(not disabled)

    @Component.reconfig_on_error
    def _get(self, data=None):
        # print("TECNA SCREWDIVER", str(int(QThread.currentThreadId())), flush=True)
        # READ INFO
        if data is None or data[-1] is None:
            return
        screwed_flag = bool(data[-1][list(self.sources)[0]]["Digital inputs status (mask)"] & self.status_pin_mask)
        screwed = screwed_flag and not self.last_screwed
        self.last_screwed = screwed_flag
        if screwed and self.enabled:
            self.disable()
            self.enable()
        info = {"screwed": screwed}
        self.log.debug(str(info))
        super()._get([info])
