import sys

from PyQt5.QtGui import QPalette
from ui.test_test import Test_Test


class Test_Resistance(Test_Test):
    def __init__(self, components=None, recipe=None, step=None, run_once=False, enable_override=False):
        super().__init__(components=components, recipe=recipe, step=step, run_once=run_once, enable_override=enable_override)
        self.ok_counter_limit = 3

    def start(self, recipe=None, step=None):
        # TESTING
        if "--test-resistance" in sys.argv or "--test" in sys.argv:
            self.simulate = True
        else:
            self.simulate = False
        # /TESTING
        expected = step.spec.get("expected", "-")
        if expected == float("+inf"):
            step.spec["expected"] = 1e9
        super().start(recipe=recipe, step=step)
        if self.run_once is True and self.done is True and self.done_ok is True:
            return
        # setup test loop
        self.components["multicomp"].set_resistance_scale(self.step.spec.get("scale", 500))
        self.get_connection = self.components["multicomp"].out.connect(self.get)
        self.components["multicomp"].resume()
        expected = self.step.spec.get("expected", "-")
        if expected == 1e9:
            self.ok_counter_limit = 1
            self.parent_assembly_widget().set_text(u"SCOLLEGARE IL CONNETTORE")
        else:
            self.ok_counter_limit = 3
            self.parent_assembly_widget().set_text(u"VERIFICARE CONTROLLO RESISTENZA")
        self.expected_l.setText(str(expected))
        tolerance = self.step.spec.get("tolerance", "-")
        self.tolerance_l.setText(str(tolerance))
        if all([
            isinstance(expected, (int, float)),
            isinstance(tolerance, (int, float)),
        ]):
            min_tolerance = expected * (1 - tolerance / 100)
            max_tolerance = expected * (1 + tolerance / 100)
        else:
            min_tolerance = "-"
            max_tolerance = "-"
        self.tolerance_min_l.setText(str(min_tolerance))
        self.tolerance_max_l.setText(str(max_tolerance))
        bg = self.status_palettes[None].color(QPalette.Background)
        color = f"rgb({bg.red()}, {bg.green()}, {bg.blue()})"
        self.resistance_l.setStyleSheet(f"background-color: {color};\nborder: 1px solid black;\n")

    def stop(self):
        # disable test loop
        self.components["multicomp"].pause()
        self.disconnect(self.get_connection)
        super().stop()

    # 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:
            data["multicomp"] = {
                "function": "\"RES\"",
                "scale": self.step.spec.get("scale", 500),
                "measure": self.step.spec.get("expected", 0),
            }
        # /TESTING
        result = data["multicomp"].get("measure", None)
        expected = self.step.spec.get("expected", "-")
        tolerance = self.step.spec.get("tolerance", "-")
        if all([
            isinstance(result, (int, float)),
            isinstance(expected, (int, float)),
            isinstance(tolerance, (int, float)),
        ]):
            if abs(result - expected) <= expected * (tolerance / 100):
                ok = True
            else:
                ok = None
        else:
            ok = None
        super().get([{
            "time": data.get("time", None),
            "results": {
                "ok": ok,
                "result": result,
                "data": data["multicomp"],
            },
        }], 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 {
            # "scale": self.scale_l,
            "measure": self.resistance_l,
        }.items():
            v = d.get(k, "-")
            if type(v) is float:
                v = round(v, 2)
            l.setText(str(v))
        ok = data.get("results", {}).get("ok", None) is True
        bg = self.status_palettes[ok].color(QPalette.Base)
        color = f"rgb({bg.red()}, {bg.green()}, {bg.blue()})"
        self.resistance_l.setStyleSheet(f"background-color: {color};\nborder: 1px solid black;\n")
        super().visualize(data)

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