import sys
from datetime import datetime

# from lib.db import Autotests
from PyQt5.QtCore import Qt, QTimer, pyqtSignal, pyqtSlot
# from PyQt5.QtGui import QPixmap
from ui.widget import Widget


class Test_Autotest(Widget):
    ok = pyqtSignal()

    def set_reason(self, reason):
        print(reason)
    # def __init__(self, bench, drawing, reason):
    #     self.reason = reason
    #     self.autotest_cycle = [
    #         ["autotest_nok", "Inserire campione autotest \"NOK\"", "autotest_nok"],
    #         ["autotest_ok", "Inserire campione autotest \"OK\"", "autotest_ok"],
    #     ]
    #     self.autotest_cycle_state = 0
    #     test = self.autotest_cycle[self.autotest_cycle_state]
    #     recipe = bench.recipes[test[0]]
    #     for h in ["wires", "terminals"]:
    #         bench.parsers[h].set_recipe(recipe)
    #     self.instructions_img = QPixmap("src/ui/imgs/{}.png".format(test[2]))
    #     log_msg("autotest {}".format(test[0]))
    #     super().__init__(bench, drawing)
    #     if "--sim-autotest" not in sys.argv:
    #         self.vision_ok_counter_limit = 3
    #     else:
    #         self.vision_ok_counter_limit = 1
    #     self.autotest_frames = {}
    #     self.cycle_state_timer = QTimer()
    #     self.cycle_state_timer.setSingleShot(True)
    #     self.cycle_state_timer.setInterval(2000)
    #     self.cycle_state_timer.timeout.connect(self.cycle_state)
    #     self.sources = ["frame", "wires", "terminals"]
    #     self.bench.inputs["renderer"].checklist = ["wires", "terminals"]
    #     self.bench.inputs["datamatrix"].update.disconnect()
    #     self.bench.inputs["datamatrix"].out.disconnect()
    #     self.instruction_l.setText(test[1])
    #     self.autotest_cycle_state_leds = [
    #         self.nok_state_l,
    #         self.ok_state_l,
    #     ]
    #     self.update_leds()
    #
    # @pyqtSlot()
    # def resizeEvent(self, event=None):
    #     super().resizeEvent(event=event)
    #     self.instructions_img_l.setPixmap(self.instructions_img.scaled(self.instructions_img_l.width(), self.instructions_img_l.height(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
    #
    # @pyqtSlot()
    # @pyqtSlot(str)
    # def check_barcodes(self, barcode=None):
    #     pass
    #
    # def check_ok(self):
    #     # CHECK IF COMPLETED AUTOTEST
    #     if (
    #         all([t in self.vision and self.vision[t]["ok"] for t in ["wires", "terminals"]])
    #         and self.vision_ok_counter >= self.vision_ok_counter_limit
    #     ):
    #         self.autotest_frames[self.autotest_cycle[self.autotest_cycle_state][0]] = self.frame
    #         self.instructions_img = QPixmap("src/ui/imgs/success.png")
    #         self.resizeEvent()
    #         self.autotest_cycle_state += 1
    #         self.cycle_state_timer.start()
    #
    # @pyqtSlot()
    # def cycle_state(self, override=False):
    #     if self.autotest_cycle_state < len(self.autotest_cycle) and not override:
    #         test = self.autotest_cycle[self.autotest_cycle_state]
    #         recipe = self.bench.recipes[test[0]]
    #         for h in ["wires", "terminals"]:
    #             self.bench.parsers[h].set_recipe(recipe)
    #             self.instruction_l.setText(test[1])
    #             self.instructions_img = QPixmap("src/ui/imgs/{}.png".format(test[2]))
    #             self.resizeEvent()
    #             log_msg("autotest {}".format(test[0]))
    #         self.request_vision.emit()
    #     else:
    #         if override:
    #             self.bench.outputs["autotest_recorder"].save(self.frame[0], self.frame[1])
    #             self.save(overridden=True)
    #         else:
    #             self.save()
    #         # RESET RECIPES TO ACTUAL ONES
    #         if self.drawing is not None:
    #             recipe = self.bench.recipes[self.drawing.vision_recipe]
    #             for h in ["wires", "terminals"]:
    #                 self.bench.parsers[h].set_recipe(recipe)
    #         self.ok.emit()
    #     self.update_leds()
    #
    # @pyqtSlot()
    # def update_leds(self):
    #     for n, led in enumerate(self.autotest_cycle_state_leds):
    #         if n < self.autotest_cycle_state:
    #             led.setPixmap(self.sled.cmp(True))
    #         elif n == self.autotest_cycle_state:
    #             led.setPixmap(self.sled.cmp("right"))
    #         elif n > self.autotest_cycle_state:
    #             led.setPixmap(self.sled.cmp(False))
    #
    # @pyqtSlot()
    # def override_vision(self):
    #     if self.challenge_admin("Si sta tentando di bypassare il l'autotest"):
    #         self.cycle_state(override=True)
    #
    # def save(self, overridden=False):
    #     frames = []
    #     for k, f in self.autotest_frames.items():
    #         frames.append(self.bench.outputs["autotest_recorder"].save(f[0], f[1]))
    #     Autotests.archive(result=True, vision_tests=[t[0] for t in self.autotest_cycle], reason=self.reason, overridden=overridden, frames=frames)
    #     self.bench.last_autotest = datetime.now()
