# (c) 2016 Claudemir de Almeida Rosa
import re
import uno, unohelper
from com.sun.star.task import XJobExecutor
from com.sun.star.awt.MessageBoxButtons import BUTTONS_OK, BUTTONS_OK_CANCEL, BUTTONS_YES_NO, BUTTONS_YES_NO_CANCEL, BUTTONS_RETRY_CANCEL, BUTTONS_ABORT_IGNORE_RETRY
from com.sun.star.awt.MessageBoxButtons import DEFAULT_BUTTON_OK, DEFAULT_BUTTON_CANCEL, DEFAULT_BUTTON_RETRY, DEFAULT_BUTTON_YES, DEFAULT_BUTTON_NO, DEFAULT_BUTTON_IGNORE

from com.sun.star.awt.MessageBoxType import MESSAGEBOX, INFOBOX, WARNINGBOX, ERRORBOX, QUERYBOX
import string
from com.sun.star.beans import PropertyValue
import json
import sys
import logging
import urllib
from urllib.request import urlopen, Request
from urllib.parse import urlencode, quote, quote_plus
if sys.platform != 'win32':
    import ssl
    myssl = ssl.create_default_context();
    myssl.check_hostname=False
    myssl.verify_mode=ssl.CERT_NONE



logging.basicConfig(filename='/tmp/TradutorLibreText.log', level=logging.INFO)




class Langerror(Exception):

    def __init__(self, language,langcode):

        Exception.__init__(self)
        if langcode=='pt-BR':
            self.language =  'O texto contem caractere ou idioma sem suporte'  +  language
        else :
            self.language =  'The text contains invalid character or language  '  +  language


class selectsize(Exception):

    def __init__(self, size,langcode):

        Exception.__init__(self)

        if langcode=='pt-BR':

            self.size ='selecione de 2 h\xE1 1900 caracteres ( Total selecionado ( '  + size + ' ))'
        else :
            self.size =    'You have selected 0 or more than 1900 characters (Total selected ( '+ size +'))'


class Tradutor(unohelper.Base, XJobExecutor):


    def __init__(self, ctx):
        self.ctx = ctx
        desktop = self.ctx.ServiceManager.createInstanceWithContext( "com.sun.star.frame.Desktop", self.ctx )
        self.dispatcher=self.ctx.ServiceManager.createInstanceWithContext( "com.sun.star.frame.DispatchHelper", self.ctx )
        self.language=self.ctx.ServiceManager.createInstanceWithContext( "com.sun.star.i18n.LocaleData", self.ctx )
        self.document = desktop.getCurrentComponent()
        self.lang=self.ctx.ServiceManager.createInstanceWithContext( "com.sun.star.configuration.ConfigurationProvider", self.ctx )


    def translate(self,text, dst_lang, src_lang='auto'):

        url = "http://translate.google.com/m?hl=%s&sl=%s&q=%s" % (dst_lang, src_lang, urllib.parse.quote_plus(text))

        req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
        if sys.platform != 'win32':
            page = urlopen(req,context=myssl).read().decode('utf-8')
        else:
            page = urlopen(req).read().decode('utf-8')
        before_trans = 'class="t0">'
        result = page[page.find(before_trans)+len(before_trans):]
        result = result.split("<")[0]
        return result


    def trigger(self, args):

        # Obtem  um texto selecionado
        controller = self.document.getCurrentController()
        selection = controller.getSelection()
        xTextRange = selection.getByIndex(0)
        string = xTextRange.getString()

        # Obtem  o idioma
        properties = []
        arg = PropertyValue()
        arg.Name = "nodepath"
        arg.Value = "/org.openoffice.Setup/L10N"
        properties.append(arg)
        properties = tuple(properties)
        aSettings= self.lang.createInstanceWithArguments("com.sun.star.configuration.ConfigurationAccess", properties)
        code= aSettings.getByName("ooLocale")
        Langinfo=self.language.getLanguageCountryInfo(xTextRange.CharLocale)


        text= string



        try:
            if len(text) > 1900 : raise selectsize(str(len(text)),code)
            elif len(text) == 0 : raise selectsize(str(len(text)),code)



            try:
                lang2=xTextRange.CharLocale.Language

                if  Langinfo.CountryDefaultName != "United States":
                    msglang = Langinfo.LanguageDefaultName + " " + Langinfo.CountryDefaultName
                else:
                    msglang = " "



                trans=self.translate(text,lang2)



                xTextRange.setString(trans.replace('\\n',"\n").replace('\\r',"\n"))

            except Exception as e:
                try:
                    self.MessageBox(e)
                except Exception as e:
                    logging.info(e)


        except Exception as e:
            try:
                self.MessageBox(str(e.size))
            except Exception as e:
                logging.info(e)


    def MessageBox(self,MsgText, MsgTitle="", MsgType=MESSAGEBOX, MsgButtons=BUTTONS_OK):
        ParentWin = self.document.getCurrentController().Frame.ContainerWindow
        ctx = uno.getComponentContext()
        sm = ctx.ServiceManager
        sv = sm.createInstanceWithContext("com.sun.star.awt.Toolkit", ctx)
        myBox = sv.createMessageBox(ParentWin, MsgType, MsgButtons, MsgTitle, MsgText)

        return myBox.execute()





g_ImplementationHelper = unohelper.ImplementationHelper()

g_ImplementationHelper.addImplementation(Tradutor,
        "org.openoffice.comp.pyuno.TradutorLibreText",
        ("com.sun.star.task.Job",),)
