import sys
import weakref

from lib.helpers import timing
from PyQt5.QtCore import QTimer
from PyQt5.QtGui import QKeySequence
from PyQt5.QtWidgets import QShortcut
from ui.test_test import Test_Test


class Test_Count(Test_Test):
    def __init__(self, components=None, recipe=None, step=None, pieces=None, run_once=False, reset_on_start=False, 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.amount_sb.setRange(0, 9999)
        self.amount = 0
        self.continue_b.clicked.connect(lambda checked, self=weakref.ref(self): self().get(self().amount_sb.value()))
        self.ignore_b.clicked.connect(lambda checked, self=weakref.ref(self): self().get(0))

    def start(self, recipe=None, step=None, pieces=None):
        show = super().start(recipe=recipe, step=step, pieces=pieces)
        if show is False:
            return show
        self.visualize()
        self.amount = self.step.spec.get("amount", 0)
        self.amount_sb.setValue(int(self.amount))
        # TESTING
        if "--test-count" in sys.argv or "--test" in sys.argv:
            self.amount_sb.setValue(1)
            self.test_timer = QTimer()
            self.test_timer.setSingleShot(True)
            self.test_timer.timeout.connect(self.continue_b.click)
            self.test_timer.start(500)
        # /TESTING
        return show

    # def stop(self):
    #     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:
        #     data = self.amount_sb.value()
        if data is None:
            super().get(None, override=override)
            return
        result = data
        ok = True
        super().get([{
            "time": timing(),
            "results": {
                "ok": ok,
                "result": result,
                "data": data,
            },
        }], override=override, fail=ok is False, skip_delay=True)
