from language_translation.translate.provider.youdao import YoudaoProvider
from textwrap import wrap

TRANSLATION_API_MAX_LENGTH = 1000

DEFAULT_PROVIDER = YoudaoProvider
PROVIDER_CLASSES = {
    "youdao": YoudaoProvider,
}


class Translator:

    def __init__(
            self,
            from_lang: str,
            to_lang: str,
            provider: str = None,
            cookie: str = None,
            region: str = None,
            **kwargs):
        self.available_providers = list(PROVIDER_CLASSES.keys())
        if provider and provider not in self.available_providers:
            raise ValueError(
                "Provider class invalid."
                "Please check providers list below: {!r}".format(self.available_providers)
            )
        self.from_lang = from_lang
        self.to_lang = to_lang

        provider_class = PROVIDER_CLASSES.get(provider, DEFAULT_PROVIDER)
        self.provider = provider_class(
            from_lang=from_lang,
            to_lang=to_lang,
            cookie=cookie,
            region=region,
            **kwargs
        )

    def translate(self, text: str) -> str | None:
        if self.from_lang == self.to_lang:
            return text
        text_list = wrap(text, TRANSLATION_API_MAX_LENGTH, replace_whitespace=False)
        return " ".join([self.provider.translate(t) for t in text_list])
