# -*- coding: utf-8 -*-
from typing import List, Union
from pygtrans import Translate, Null
from ddans.native.hook import NHook
from ddans.config.locale import DEFAULT_LANG
from ddans.native.log import NLog
from ddans.native.system import NSystem
from ddans.native.time import NTime


class Gi18n:

    def __init__(self, lang: str = DEFAULT_LANG, source: str = 'auto'):
        self.lang = lang
        self.source = source

    def is_success(self, res):
        if isinstance(res, Null):
            return False
        else:
            return True

    def get_client(self):
        proxy = NSystem.get_proxy()
        if NHook.isvalid_str(proxy):
            return Translate(proxies={'https': f'http://{proxy}'})
        else:
            return Translate()

    def done(self,
             q: Union[str, List[str]],
             lang: str = None,
             source: str = None,
             retries: int = 0):
        try:

            if lang is None:
                lang = self.lang
            if source is None:
                source = self.source

            temps = []
            if isinstance(q, str):
                if NHook.isvalid_str(q):
                    temps = [q]
                else:
                    return None
            elif isinstance(q, list):
                temps = q
            else:
                return None

            lists = [
                item for item in temps if isinstance(item, str)
                and item.strip() != '' and temps.count(item) == 1
            ]

            count = len(lists)
            if count <= 0:
                return None

            map = dict()

            client = self.get_client()
            # 翻译
            results = client.translate(lists, lang, source=source, fmt="text")

            for i in range(min(count, len(results))):
                key = lists[i]
                val = results[i]

                if not self.is_success(val):
                    continue

                txt = val.translatedText
                if NHook.isvalid_str(txt):
                    map[key] = txt
            return map
        except Exception as e:
            if retries > 0:
                NTime.sleep(1)
                return self.done(q, lang, source, retries=retries - 1)
            else:
                NLog.error(f"translate {lang}: {e}")
                return None
