import pspnet, psp2d, urllib, thread,time

statusTrad = 0
## 
## PSPDictionary
## Copyright (C) 2009,2010 Germano Fabio
## gefasio@gmail.com
## 
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## 
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
## 
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
##

statusCon = 0
traduzioni = tuple()

def _connect(self):
    global statusCon
    pspnet.connectToAPCTL(config = 0)
    statusCon = 1

def connect():
    thread.start_new_thread(_connect, (None,))

def Traduci(server, datradurre, lingua, lingua1):
    '''
    Funzione adibita alla traduzione online, appoggiandosi ai server:
        - it.babelfish.yahoo.com;
        - langtolang.com;
        - google.translate.com
    '''
    if server == 'it.babelfish.yahoo.com/':
        # Server -> it.babelfish.yahoo.com/
        url = urllib.urlopen('http://'+server+'translate_txt?type=text&text='+datradurre.replace(' ','+')+\
                             '&url=http%3A%2F%2F&lp='+lingua+'&Submit=Translate')
        src = url.read()
        url.close()
        dove = src.find('<div id="result"><div style="padding:0.6em;">')
        traduzione = ''
        for lettera in src[dove+len("""<div id="result"><div style="padding:0.6em;">"""):dove+150]:
            if not lettera == '<':
                traduzione += lettera
            else:
                break
        print traduzione
        return traduzione # string
    elif server == 'langtolang.com':
        url = urllib.urlopen("http://www.langtolang.com/?selectFrom="+lingua+"&selectTo="+lingua1+"&txtLang="+datradurre+"&submitButton=Search")       
        toparse0 = url.read()
        toparse = toparse0.replace('\t','')
        url.close()
        traduzioniTemp = []
        for i in range(toparse.find("""<table width="100%" cellpadding="1" cellspacing="0">"""),\
                       toparse.find("""<tr><td><div id="userSuggestion"></div>To make suggestion with your username please""")):
            if toparse[i:i+len("""<td width="40%">""")] == """<td width="40%">""":
                parola = ''
                for lettera in toparse[i+len("""<td width="40%">"""):len(toparse)]:
                    if lettera == '<':
                        if not parola == datradurre:
                            traduzioniTemp.append(parola)
                        break  
                    parola += lettera
        print traduzioniTemp
        if len(traduzioniTemp) != 0:
            return traduzioniTemp # list
        else:
            traduzioniTemp.append("No translation found for '"+datradurre+"'.")
            return traduzioniTemp # list
    elif server == 'google.translate.com':
        url = urllib.urlopen("http://www.psp-ita.com/pspdictionary/?lang="+lingua+"&text="+datradurre.replace(' ','+')+"&pass=16253745374")
        src = url.read()
        url.close()
        return src # string

## Evitiamo di avviare nuovi thread...
#def Traduci():
#    thread.start_new_thread(_Traduci, (lingua, parola))
