from . import command, reply_fn
from langdetect import detect
import gtts
import threading
import io
import logging
import re
import requests
import time

logger = logging.getLogger('tts')

def fetch_chunks_and_send_voice(bot, channel, chunks, lang):
    endpoint = 'https://tts.segfault.party/tts'
    buf = io.BytesIO()
    for n in range(len(chunks)):
        chunk = chunks[n]
        logger.info(f'Fetching speech for chunk: {chunk!r}')
        params = {'locale': lang, 'text': chunk}
        resp = requests.get(endpoint, params=params)
        if resp.status_code == 400:
            bot.send_message(chat_id=channel, text='Kon helaas niet alle chunks bij iSpeech ophalen; chunk te lang?')
            return
        else:
            buf.write(resp.content)

    buf.seek(0)
    bot.send_voice(channel, buf)

@command('leest veur', additional_match_fn=reply_fn)
def lees_voor_ispeech(bea, bot, update, reply):
    if not reply.text:
        return
    read_helper(bea, bot, update, reply.text)

@command('zeg (.+)', pass_groups=True)
def zeg(bea, bot, update, groups):
    text = groups[0]
    read_helper(bea, bot, update, text)

def read_helper(bea, bot, update, text):
    chunks = re.split(r'(?<=[.;?])\s+', text)
    modified_chunks = []
    for chunk in chunks:
        if len(chunk) > 150:
            words = chunk.split(' ')
            segment = words[0]
            for word in words[1:]:
                proposed_segment = segment + ' ' + word
                if (len(proposed_segment) > 150):
                    modified_chunks.append(segment)
                    segment = word
                else:
                    segment = proposed_segment
            modified_chunks.append(segment)
        else:
            modified_chunks.append(chunk)

    threading.Thread(target=fetch_chunks_and_send_voice, args=(bot, update.effective_chat.id, modified_chunks, 'eurdutchfemale'), daemon=True).start()

@command('lees voor', additional_match_fn=reply_fn)
def lees_voor(bea, bot, update, reply):
    if (not reply.text):
        return

    ccode = detect(reply.text)

    logger.info(f"detected language: {ccode}")

    tts = gtts.gTTS(text=reply.text, lang=ccode)
    buf = io.BytesIO()

    try:
        tts.write_to_fp(buf)
    except gtts.gTTSError as e:
        return bea.reply(f"Sorry, dat werkte niet: {e.infer_msg(tts)}")

    buf.seek(0)

    update.message.reply_voice(buf)

def init(bea, _):
    return [zeg, lees_voor_ispeech, lees_voor]
