import re
import sys
import weakref

from lib.helpers import timing
from PyQt5.QtCore import QTimer
from PyQt5.QtGui import QKeySequence
from PyQt5.QtWidgets import QShortcut
from ui.test_test import Test_Test


class Test_Fail(Test_Test):
    def __init__(self, recipe=None, step=None, pieces=None, run_once=False, reset_on_start=True, enable_override=False,parent=None):
        super().__init__(components=parent.components, recipe=recipe, step=step, pieces=pieces, run_once=run_once, reset_on_start=reset_on_start, enable_override=enable_override)
        self.continue_b.clicked.connect(lambda checked, self=weakref.ref(self): self().ok.emit(None))
        self.parent=parent
        self.discard_timer=QTimer()
        self.discard_timer.timeout.connect(self.wait_discard)

    def start(self, recipe=None, step=None, pieces=None):
        show = super().start(recipe=recipe, step=step, pieces=pieces)
        if show is False:
            return show
        if "discard_box" in self.parent.config["hardware_config"].keys():
            if self.parent.require_discard_piece:
                if self.parent_assembly_widget is not None :
                    self.continue_b.setVisible(False)
                    self.discard_timer.start(100)
                    self.parent_assembly_widget().set_text(text="TEST KO - INSERIRE IL PEZZO COLLAUDATO NEL CONTENITORE DI SEGREGAZIONE SCARTI",text_color="black",bg_color="red")
                    self.io_connection=self.components["digital_io"].out.connect(self.wait_discard)

        self.visualize()
        # TESTING
        if "--test" in sys.argv:
            self.test_timer = QTimer()
            self.test_timer.setSingleShot(True)
            self.test_timer.timeout.connect(self.continue_b.click)
            self.test_timer.start(500)
        return show

    def stop(self):
        if "discard_box" in self.parent.config["hardware_config"].keys():
            if hasattr(self,"io_connection"):
                self.disconnect(self.io_connection)
        super().stop()

    def wait_discard(self,data=None):
        if data is not None:
            if len(data[0]["digital_io"]) == 0:
                return
            else:
                sensor_index = int(self.parent.config["digital_io"]["discard_idx"])
                byte_idx = int(sensor_index / 8)
                bit_idx = sensor_index % 8
                if not data[0]["digital_io"][byte_idx][bit_idx]:
                    self.ok.emit(None)

