1# -*- coding: utf-8 -*-
2#
3#  Copyrignt (C) 2017 Jordi Mas <jmas@softcatala.org>
4#
5#  This program is free software; you can redistribute it and/or modify
6#  it under the terms of the GNU General Public License as published by
7#  the Free Software Foundation; either version 2 of the License, or
8#  (at your option) any later version.
9#
10#  This program is distributed in the hope that it will be useful,
11#  but WITHOUT ANY WARRANTY; without even the implied warranty of
12#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13#  GNU General Public License for more details.
14#
15#  You should have received a copy of the GNU General Public License
16#  along with this program; if not, write to the Free Software
17#  Foundation, Inc., 51 Franklin Street, Fifth Floor,
18#  Boston, MA 02110-1301, USA.
19
20import urllib.request, urllib.parse, urllib.error
21import json
22from .service import Service
23
24try:
25    import gettext
26    gettext.bindtextdomain('gedit-plugins')
27    gettext.textdomain('gedit-plugins')
28    _ = gettext.gettext
29except:
30    _ = lambda s: s
31
32
33class Yandex(Service):
34
35    g_language_codes = []
36    g_language_names = []
37    g_locales_names = {}
38
39    DEFAULT_LANGUAGE_NAMES = ["Spanish -> English",
40            "English -> Spanish",
41            "Catalan -> English",
42            "English -> Catalan"]
43
44    DEFAULT_LANGUAGE_CODES = ["es|en",
45            "en|es",
46            "ca|en",
47            "en|ca",
48    ]
49
50    SERVER = "https://translate.yandex.net/api/v1.5/tr.json"
51
52    g_language_codes = []
53    g_language_names = []
54
55    @staticmethod
56    def _clean_for_ut():
57        Yandex.g_language_codes = []
58        Yandex.g_language_names = []
59        Yandex.g_locales_names = {}
60
61    def get_default_language_codes(self):
62        return 'en|es'
63
64    def get_api_hint(self):
65        return _("You need to obtain an API key at <a href='https://tech.yandex.com/translate/'>https://tech.yandex.com/translate/</a>")
66
67    def has_api_key(self):
68        return True
69
70    def set_api_key(self, key):
71        self._key = key
72
73    def set_server(self, server):
74        pass
75
76    def init(self):
77        self._fetch_remote_language_names()
78
79    def get_language_names(self):
80        if len(Yandex.g_language_codes) > 0 and len(Yandex.g_language_names) > 0:
81            return Yandex.g_language_names
82
83        return self.DEFAULT_LANGUAGE_NAMES
84
85    def get_language_codes(self):
86        if len(Yandex.g_language_codes) > 0 and len(Yandex.g_language_names) > 0:
87            return Yandex.g_language_codes
88
89        return self.DEFAULT_LANGUAGE_CODES
90
91    def get_language_pair_name(self, source, target, locales_names=None):
92        if locales_names is None:
93            locales_names = Yandex.g_locales_names
94
95        source = self._get_language_name(source, locales_names)
96        target = self._get_language_name(target, locales_names)
97        return "{0} -> {1}".format(source, target)
98
99    def _get_language_name(self, langcode, locales_names):
100        return locales_names[langcode]
101
102    def _fetch_remote_language_names(self):
103
104        try:
105
106            if len(self._key) == 0:
107                return
108
109            if (len(Yandex.g_locales_names) > 0 and
110               len(Yandex.g_language_names) > 0 and
111               len(Yandex.g_language_codes) > 0):
112                    return
113
114            url = "{0}/getLangs?ui=en&key={1}".format(self.SERVER, self._key)
115            response = urllib.request.urlopen(url)
116            payload = json.loads(response.read().decode("utf-8"))
117
118            language_codes = payload['dirs']
119            language_codes = [x.replace('-', '|') for x in language_codes]
120            locales_names = payload['langs']
121
122            language_names = []
123            for lang_pair in language_codes:
124                langs = lang_pair.split('|')
125                source = langs[0]
126                target = langs[1]
127                name = self.get_language_pair_name(source, target, locales_names)
128                language_names.append(name)
129
130            Yandex.g_locales_names = locales_names
131            Yandex.g_language_names = language_names
132            Yandex.g_language_codes = language_codes
133
134        except Exception as e:
135            print("_fetch_remote_language_names exception {0}".format(e))
136
137    def translate_text(self, text, language_pair):
138        language_pair = language_pair.replace('|', '-')
139        url = "{0}/translate?lang={1}&format=plain&key={2}".format(self.SERVER, language_pair, self._key)
140        url += "&text=" + urllib.parse.quote_plus(text.encode('utf-8'))
141        response = urllib.request.urlopen(url)
142        r = response.read().decode("utf-8")
143        data = json.loads(r)
144        all_text = ''
145
146        texts = data['text']
147        for text in texts:
148            all_text += text
149        return all_text
150