import sys
import time
import weakref

from PyQt5.QtWidgets import QMessageBox

from ui.test_test import Test_Test
from components.Automation.BDaq import ErrorCode

class Test_Leak(Test_Test):
    def __init__(self, components=None, recipe=None, step=None, pieces=None, run_once=False, reset_on_start=True, enable_override=False,parent=None):
        super().__init__(components=components, recipe=recipe, step=step, pieces=pieces, run_once=run_once, reset_on_start=reset_on_start, enable_override=enable_override)
        self.step=step
        self.start_b.clicked.connect(self.start_test)
        self.stop_b.clicked.connect(lambda checked, self=weakref.ref(self): self().components["tecna_t3"].stop_test())
        self.parent=parent

    def start_test(self):
        # print extra labels
        if self.step.type == "leak_1":
            self.parent.print_extra_labels()
            self.components["tecna_t3"].start_test()

    def start(self, recipe=None, step=None, pieces=None):
        # TESTING
        if "--test-leak" in sys.argv or "--test" in sys.argv:
            self.simulate = True
        else:
            self.simulate = False
        # /TESTING
        show = super().start(recipe=recipe, step=step, pieces=pieces)
        if show is False:
            return show

        # setup test loop
        self.components["tecna_t3"].write_recipe(self.recipe, self.step)
        self.get_connection = self.components["tecna_t3"].out.connect(self.get)
        self.components["tecna_t3"].resume()
        if self.parent_assembly_widget is not None:
            self.parent_assembly_widget().set_text(text="WAIT")
        self.start_b.setEnabled(False)
        self.stop_b.setEnabled(False)

        # SETUP RELAY CONFIGURATION
        if "digital_io" in self.components.keys():
            if "relay_config" in step.spec.keys():
                relay_config = step.spec["relay_config"]
                bits = [0, 0]
                if relay_config == 0:
                    bits = [0,0]
                if relay_config == 1:
                    bits = [0,1]
                if relay_config == 2:
                    bits = [1,0]

                ret=self.components["digital_io"].set_bit_verify(0, 0, bits[1])
                ret=self.components["digital_io"].set_bit_verify(0, 1, bits[0])

                if ret:
                    time.sleep(1)
                    # AUTO START SECOND TEST
                    if step.type == "leak_2":
                        self.start_b.setEnabled(True)
                        self.start_b.click()
                else:
                    QMessageBox.critical(None, "Errore", f"Errore di pilotaggio elettrovalvole")
        return show

    def stop(self):
        # disable test loop
        self.components["tecna_t3"].stop_test()
        self.components["tecna_t3"].pause()
        self.disconnect(self.get_connection)
        super().stop()
        if self.parent_assembly_widget is not None:
            self.parent_assembly_widget().set_text(text="WAIT")
        self.start_b.setEnabled(False)
        self.stop_b.setEnabled(False)

    def get(self, data=None, override=False):
        if self.done:  # avoid processing if completed
            return
        if data is None or data[-1] is None:
            super().get(None, override=override)
            return
        data = data[-1]

        # TESTING
        if self.simulate:
            if self.step.spec.get("autotest", False) is not True:
                data["tecna_t3"] = {
                    "Running test: result": "-----TESTING----- passed",
                }
            else:
                data["tecna_t3"] = {
                    "Running test: result": "-----TESTING----- failed",
                }

        if "Running test: result" in data["tecna_t3"]:
            result = data["tecna_t3"]["Running test: result"]
            if self.step.spec.get("autotest", False) is not True:
                ok = type(result) is str and "passed" in result.lower()
            else:
                ok = type(result) is str and "failed" in result.lower()

            if "digital_io" in self.components.keys():
                # RESET RELAYS
                ret = self.components["digital_io"].set_bit_verify(0, 0, 0)
                ret = self.components["digital_io"].set_bit_verify(0, 1, 0)

        else:
            result = None
            ok = None
        super().get([{
            "time": data.get("time", None),
            "results": {
                "ok": ok,
                "result": result,
                "data": data["tecna_t3"],
            },
        }], override=override, fail=ok is False)

    def visualize(self, data=None):
        if data is None:
            data = {}
        d = data.get("results", {}).get("data", {})
        for k, l in {
            "Running test: active phase": self.test_phase_l,
            "Real time test pressure output": self.circuit_pressure_l,
            "Real time differential pressure output": self.leak_l,
            "Real time pressure line regulator": self.regulated_pressure_l,
            # "Active alarm flags": self._l,
            "Running test: test type": self.test_type_l,
            "Running test: sequence index": self.sequence_index_l,
        }.items():
            v = d.get(k, "-")
            if type(v) is float:
                v = round(v, 2)
            l.setText(str(v))
        if d.get("Running test: active phase", None) in {
            "WAITING START",
            "ATTESA START",
            "END TEST, WAITING THE START OF A NEW TEST"
            "FINE TEST",
        }:
            if self.step.spec.get("autotest", False) is not True:
                if self.parent_assembly_widget is not None:
                    self.parent_assembly_widget().set_text(text="COLLEGARE GLI ATTACCHI PNEUMATICI E PREMERE START PER INIZIARE LA PROVA TENUTA")
            else:
                if self.parent_assembly_widget is not None:
                    self.parent_assembly_widget().set_text(text="AUTOTEST: COLLEGARE LA FUGA CALIBRATA E PREMERE START PER INIZIARE LA PROVA TENUTA DI PROVA",color="blue")
            self.start_b.setEnabled(True)
            self.stop_b.setEnabled(False)
        else:
            if self.step is not None:
                if self.step.spec.get("autotest", False) is not True:
                    if self.parent_assembly_widget is not None:
                        self.parent_assembly_widget().set_text(text="PROVA TENUTA IN CORSO")
                else:
                    if self.parent_assembly_widget is not None:
                        self.parent_assembly_widget().set_text(text="AUTOTEST: PROVA TENUTA IN CORSO")
            self.start_b.setEnabled(False)
            self.stop_b.setEnabled(True)
        ok = data.get("results", {}).get("ok", None)
        super().visualize(data, img=self.status_imgs_full[ok])

    def save_last(self):
        if self.last is None:
            return
