#encoding = utf8

import logging
import time

from nlp import NLPCallback
from utils import AsyncTaskQueue

logger = logging.getLogger(__name__)


class TTSBase(NLPCallback):
    def __init__(self, handle):
        self._handle = handle
        self._message_queue = AsyncTaskQueue(5)

    @property
    def handle(self):
        return self._handle

    @handle.setter
    def handle(self, value):
        self._handle = value

    async def _request(self, txt: str, index):
        print('_request:', txt)
        t = time.time()
        stream = await self._on_request(txt)
        if stream is None:
            print(f'-------stream is None')
            return
        print(f'-------tts time:{time.time() - t:.4f}s')
        await self._on_handle(stream, index)

    async def _on_request(self, text: str):
        pass

    async def _on_handle(self, stream, index):
        pass

    async def _on_close(self):
        pass

    def on_message(self, txt: str):
        self.message(txt)

    def message(self, txt):
        txt = txt.strip()
        if len(txt) == 0:
            logger.info(f'message is empty')
            return
        logger.info(f'message:{txt}')
        index = 0
        if self._handle is not None:
            index = self._handle.get_index()
            print(f'message txt-index:{txt}, index {index}')
        self._message_queue.add_task(self._request, txt, index)

    def stop(self):
        self._message_queue.add_task(self._on_close)
        self._message_queue.stop()

    def pause_talk(self):
        self._message_queue.clear()
