#encoding = utf8
import logging
import time
from abc import ABC, abstractmethod
from queue import Queue
from threading import Event, Thread

logger = logging.getLogger(__name__)


class BaseRender(ABC):
    def __init__(self, play_clock):
        self._play_clock = play_clock
        self._queue = Queue()
        self._exit_event = Event()
        self._thread = Thread(target=self._on_run)
        self._exit_event.set()
        self._thread.start()

    def _on_run(self):
        logging.info('Audio render run')
        while self._exit_event.is_set():
            self.__run_step()
            time.sleep(0.02)

        logging.info('Audio render exit')

    def put(self, frame):
        ps = time.time() - self._play_clock.start_time()
        self._queue.put_nowait((frame, ps))

    def stop(self):
        self._queue.queue.clear()
        self._exit_event.clear()
        self._thread.join()

    @abstractmethod
    def __run_step(self):
        pass


