import re
import urllib
from json import JSONDecodeError

import requests
import time

from core.command_param_types import Any
from core.decorators import instance, command, setting
from core.igncore import IgnCore
from core.registry import Registry
from core.setting_service import SettingService
from core.setting_types import TextSettingType
from core.text import Text

language_codes = [
    'af', 'am', 'ar', 'az', 'be', 'bg', 'bn', 'bs', 'ca', 'cs', 'cy', 'da', 'de', 'el',
    'en', 'es', 'et', 'eu', 'fa', 'fi', 'fil', 'fo', 'fr', 'ga', 'gl', 'gu', 'he', 'hi',
    'hr', 'hu', 'hy', 'id', 'is', 'it', 'ja', 'ka', 'kk', 'km', 'kn', 'ko', 'ky', 'lo',
    'lt', 'lv', 'mk', 'ml', 'mn', 'mr', 'ms', 'my', 'nb', 'ne', 'nl', 'pa', 'pl', 'pt',
    'ro', 'ru', 'si', 'sk', 'sl', 'sq', 'sr', 'sv', 'sw', 'ta', 'te', 'th', 'ti', 'to',
    'tr', 'uk', 'und', 'ur', 'uz', 'vi', 'yue', 'zh', 'zu' ]


@instance()
class TranslationController:
    uri = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=%s&tl=%s&dt=t&q=%s"
    last_msg = 0

    def inject(self, registry: Registry):
        self.bot: IgnCore = registry.get_instance("bot")
        self.text: Text = registry.get_instance("text")
        self.setting_service: SettingService = registry.get_instance("setting_service")


    @setting(name="default_target", value="en", description="Default target language for translations")
    def default_target(self) -> TextSettingType:
        return TextSettingType(language_codes)

    @command(command="translate", params=[Any("string")], access_level="member",
             description="Translates messages to English via the Google API")
    def translate(self, _, string):
        if left := self.last_msg+10 > time.time():
            return f"Translating is on cooldown, to prevent spamming the service. " \
                   f"Please try again in <highlight>{(self.last_msg+10)-time.time():.2f}</highlight> seconds."
        self.last_msg = time.time()
        sl = "auto"
        tl = self.default_target().get_value()
        text = ""
        if match := re.match("^([a-zA-Z]{1,3}) ([a-zA-Z]{1,3}) (.+)$", string.replace("\n", "<br>"), re.S):
            a, b, c = match.groups()
            if a in language_codes and b in language_codes:
                sl, tl, text = a, b, c
        if text == "":
            if match := re.match("^([a-zA-Z]{1,3}) (.+)$", string.replace("\n", "<br>"), re.S):
                b, c = match.groups()
                if b in language_codes:
                    tl, text = b, c
        if text == "":
            text = string
        res = requests.get(self.uri % (urllib.parse.quote(sl),
                                       urllib.parse.quote(tl),
                                       urllib.parse.quote(text, safe="")))
        try:
            res = res.json()
        except JSONDecodeError as e:
            return f"There was an error while translating your message: {res.text}"
        orig = ""
        trans = ""
        for i in res[0]:
            orig = f"{orig} {i[1]} ".strip()
            trans = f"{trans} {i[0]} ".strip()

        return f"[<notice>{res[2].upper()}</notice>] {orig}<br>[<notice>{tl.upper()}</notice>] {trans}"

    # Taken from: https://github.com/rspeer/langcodes/blob/master/langcodes/language_lists.py

