#encoding = utf8
import logging
import time
from queue import Empty

import numpy as np

from audio_render import AudioRender
from base_render import BaseRender

logger = logging.getLogger(__name__)


class VoiceRender(BaseRender):
    def __init__(self, play_clock):
        super().__init__(play_clock)
        self._audio_render = AudioRender()

    def __run_step(self):
        try:
            audio_frames, ps = self._queue.get(block=True, timeout=0.01)
        except Empty:
            return

        self._play_clock.update_display_time()
        self._play_clock.current_time = ps

        for audio_frame in audio_frames:
            frame, type_ = audio_frame
            frame = (frame * 32767).astype(np.int16)

            if self._audio_render is not None:
                try:
                    self._audio_render.write(frame.tobytes(), int(frame.shape[0] * 2))
                except Exception as e:
                    logging.error(f'Error writing audio frame: {e}')
