# app/runtime/subscribers/base_subscriber.py

import queue
import threading



class BaseSubscriber:

    def __init__(self):

        self.queue = queue.Queue(maxsize=10000)
        self._stop_event = threading.Event()

        self.thread = threading.Thread(
            target=self.run,
            daemon=True
        )
    
    def stop(self):
        self._stop_event.set()

    def start(self):
        if self.thread is not None and self.thread.is_alive():
            return
        
        self._stop_event.clear()
        self.thread.start()

    def publish(self, event):

        try:
            self.queue.put_nowait(event)
        except queue.Full:
            pass 
        except:
            pass

    def run(self):
        while not self._stop_event.is_set():
            try:
                event = self.queue.get(timeout=1)
                self.handle(event)

            except queue.Empty:
                continue

            except Exception as e:
                print(e)

    def handle(self, event):

        raise NotImplementedError
    