
import threading
import time

class Counter:
    """
    Threaded counter that accumulates value based on speed.
    Can be used for rotation or animation in GUI apps.
    """

    def __init__(self, start_value=0.0, speed=0.0, name=""):
        self.value = start_value
        self.speed = speed
        self.name = name

        self._stop_event = threading.Event()
        self._lock = threading.Lock()
        self._thread = None

    def _run(self):
        while not self._stop_event.is_set():
            with self._lock:
                self.value += 0.1 * self.speed
            # Sleep briefly to allow responsive thread exit
            self._stop_event.wait(0.1)
    
    def start_counting(self):
        if self._thread is None or not self._thread.is_alive():
            self._stop_event.clear()
            self._thread = threading.Thread(target=self._run, name=f"Counter-{self.name}", daemon=True)
            self._thread.start()

    def stop_counting(self):
        self._stop_event.set()
        if self._thread is not None:
            self._thread.join()
            self._thread = None

    def reset(self, value=0.0):
        with self._lock:
            self.value = value

    def set_speed(self, speed):
        with self._lock:
            self.speed = speed

    def get_value(self):
        with self._lock:
            return self.value