import io
import time
from ntpath import join

from fastapi import Request, Response, status
from fastapi.responses import JSONResponse
from .blackbox import Blackbox
from ..tts.tts_service import TTService
from injector import singleton

@singleton
class TTS(Blackbox):

    def __init__(self, *args, **kwargs) -> None:
        self.tts_service = TTService("catmaid")

    def __call__(self, *args, **kwargs):
        return self.processing(*args, **kwargs)

    def processing(self, *args, **kwargs) -> io.BytesIO:
        text = args[0]
        current_time = time.time()
        audio = self.tts_service.read(text)
        print("#### TTS Service consume : ", (time.time()-current_time))
        return audio

    def valid(self, *args, **kwargs) -> bool:
        text = args[0]
        return isinstance(text, str)

    async def fast_api_handler(self, request: Request) -> Response:
        try:
            data = await request.json()
        except:
            return JSONResponse(content={"error": "json parse error"}, status_code=status.HTTP_400_BAD_REQUEST)
        text = data.get("text")
        if text is None:
            return JSONResponse(content={"error": "text is required"}, status_code=status.HTTP_400_BAD_REQUEST)
        by = self.processing(text)
        return Response(content=by.read(), media_type="audio/wav", headers={"Content-Disposition": "attachment; filename=audio.wav"})