import sys
import weakref

from ui.test_test import Test_Test


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):
        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.start_b.clicked.connect(lambda checked, self=weakref.ref(self): self().components["tecna_t3"].start_test())
        self.stop_b.clicked.connect(lambda checked, self=weakref.ref(self): self().components["tecna_t3"].stop_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)
        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 reset(self):
    #     super().reset()

    def get(self, data=None, override=False):
        if self.done:  # avoid proccessing 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",
                }
        # /TESTING
        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()
        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 GLI ATTACCHI PNEUMATICI CALIBRATI E PREMERE START PER INIZIARE LA PROVA TENUTA DI PROVA")
            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 DI PROVA 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
