#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, context, type_, delay=0.02):
        self._play_clock = play_clock
        self._context = context
        self._type = type_
        self._delay = delay
        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(f'{self._type} render run')
        while self._exit_event.is_set():
            self._run_step()
            time.sleep(self._delay)

        logging.info(f'{self._type} render exit')

    def put(self, frame, ps):
        self._queue.put_nowait((frame, ps))

    def size(self):
        return self._queue.qsize()

    def pause_talk(self):
        self._queue.queue.clear()

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

    @abstractmethod
    def _run_step(self):
        pass


