import sys
import weakref

from ui.test_test import Test_Test


class Test_Screws(Test_Test):
    def __init__(self, components=None, recipe=None, step=None, pieces=None, run_once=False, reset_on_start=True, enable_override=True):
        super().__init__(components=components, recipe=recipe, step=step, pieces=pieces, run_once=run_once, reset_on_start=reset_on_start, enable_override=enable_override)

    def start(self, recipe=None, step=None, pieces=None):
        # TESTING
        if "--test-screws" 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.get_connection = self.components["screwdriver"].out.connect(self.get)
        self.components["tecna_t3"].resume()
        self.components["screwdriver"].resume()
        self.ok_counter_limit = self.step.spec.get("quantity", 0)
        self.screws_counter_l.setText(str(0))
        self.screws_expected_l.setText(str(self.ok_counter_limit))
        self.components["screwdriver"].enable(self.ok_counter_limit > 0)
        return show

    def stop(self):
        # disable test loop
        self.components["screwdriver"].disable()
        self.components["screwdriver"].pause()
        self.components["tecna_t3"].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
            self.components["screwdriver"].disable()
            return
        if data is None or data[-1] is None:
            super().get(None, override=override)
            return
        data = data[-1]
        if data["screwdriver"].get("screwed", False):
            result = True
            ok = True
        else:
            result = None
            ok = None
        super().get([{
            "time": data.get("time", None),
            "results": {
                "ok": ok,
                "result": result,
                "data": data["screwdriver"],
            },
        }], override=override, preserve_counter=True)

    def visualize(self, data=None):
        if data is None:
            data = {}
        d = data.get("results", {}).get("data", {})
        if d.get("screwed", None):
            self.screws_counter_l.setText(str(self.ok_counter))
        super().visualize(data)

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