import pspnet, psp2d, urllib, thread,time
from danzeff import *
from offline import TradOffline
from online import *

class Application(object):
    def __init__(self):
        self.bg = []
        self.bg.append(psp2d.Image("img/matita_sel.png")) # 0
        self.bg.append(psp2d.Image("img/lente_sel.png"))  # 1
        self.bg.append(psp2d.Image("img/ok_sel.png"))     # 2
        self.bg.append(psp2d.Image("img/crono_sel.png"))  # 3
        self.bgLenteOn = psp2d.Image("img/lente_sel_on.png")
        self.qualeBg = 0
        self.fnt = psp2d.Font("img/font.png")
        self.textbar = psp2d.Image("img/textbar.png")
        self.box_trad_off = psp2d.Image("img/box_trad_off.png")
        self.box_connecting = psp2d.Image("img/box_conn.png")
        self.box_chron = psp2d.Image("img/box_chron.png")
        self.box_no_trad = psp2d.Image("img/box_no_trad.png")
        self.switch = [psp2d.Image("img/off.png"), psp2d.Image("img/on.png")]
        self.val = '' # For the Danzeff library.
        self.oldpad = psp2d.Controller()
        self.screen = psp2d.Screen()
        self.modalita = 'offline' # It can be: 'offline' or 'online'.
        self.tradotto = 0 # 0 -> Non ancora tradotto; 1 -> Tradotto offline; 2 -> Tradotto online.
        self.connecting = False
        self.trad = None
        self.showChron = False

        ## Var for offLine Mode
        self.vocabolariOff = {0:"English",1:"Italiano",2:"Francais",3:"Deutsche",4:"Espanol"}
        self.vocabolarioOff = 0

        self.server = 0 # 0 -> 'it.babelfish.yahoo.com/', 1 -> 'langtolang.com', 2 -> 'translate.google.com'
        self.serverDaVis = 0

        ## Var for BabelFlish server
        self.indiceOnlineBabel = 0
        self.lingueOnlineBabel = {0:'it_en',1:'it_fr',2:'fr_it',3:'en_it',4:'en_nl',5:'en_fr',6:'en_de',7:'en_es',8:'en_pt',\
                                 9:'pt_en',10:'pt_fr',11:'es_en',12:'es_fr',13:'nl_en',14:'nl_fr',15:'fr_nl',16:'fr_en',17:'fr_de',\
                                 18:'fr_pt',19:'fr_es',20:'de_en',21:'de_fr'}
        self.visualizzazioniOnlineBabel = {'it':'Italiano','en':'English','fr':'Francais','nl':'Nederlands','de':'Deutsche','pt':'Portugues',\
                                           'es':'Espanol'}
        self.traduzioniBabel = []

        ## Var for langtolang server
        self.indiceOnlineLang = 0
        self.lingueOnlineLang = {0:'english->italian', 1:'english->french',2:'english->german', 3:'english->spanish', 4:'italian->english',\
                                 5:'italian->french',  6:'italian->german',7:'italian->spanish',  8:'french->english', 9:'french->italian',\
                                 10:'french->german',11:'french->spanish',  12:'german->english',  13:'german->italian', 14:'german->french',\
                                 15:'german->spanish',  16:'spanish->english',  17:'spanish->italian',  18:'spanish->french', 19:'spanish->german'}
        self.traduzionilang = ''

        ## Var for Google translate server
        self.indiceOnlineGoogle = 0
        ## Per i dizionari, usiamo gli stessi di langtolang :-)
        self.traduzioniGoogle = ''
        
        self.Update()
    def startDanzeff(self):
        danzeff_load()						
	if (not danzeff_isinitialized()):	
		return
	danzeff_moveTo(480/2-75,100)
	while True:
                if self.tradotto == 1:
                    self.screen.blit(self.box_trad_off, 0, 0, self.box_trad_off.width, self.box_trad_off.height, 15, 73, True)
                    try:
                        self.screen.drawText(87, 95, self.trad.traduzioni[1], psp2d.Color(128,128,128))
                        self.screen.drawText(87, 95+15, self.trad.traduzioni[0], psp2d.Color(128,128,128))
                        self.screen.drawText(87, 95+30, self.trad.traduzioni[2], psp2d.Color(128,128,128))
                        self.screen.drawText(87, 95+45-2, self.trad.traduzioni[3], psp2d.Color(128,128,128))
                        self.screen.drawText(87, 95+60-3, self.trad.traduzioni[4][0:len(self.trad.traduzioni[4])-2], psp2d.Color(128,128,128))
                    except:
                        pass
                elif self.tradotto == 2:
                    self.screen.blit(self.box_no_trad, 0, 0, self.box_no_trad.width, self.box_no_trad.height, 15, 73, True)
                    self.showOnlineTrad(self.server)
                    
		danzeff_render() 
		cha = danzeff_readInput(psp2d.Controller())
		# Now Evaluate return value and take proper action
		if (cha != 0 and cha != 1 and cha != 2):
			if (cha == 8):
				self.val = self.val[0:len(self.val)-1]
			elif (cha == 13):
				self.val = ""
			elif (cha == 4):
				return
			else:
                            if len(self.val) < 55:
				self.val = self.val + chr(cha)
		self.screen.blit(self.textbar, 0, 0, self.textbar.width, self.textbar.height, 15, 46, True)
		self.screen.drawText(18, 50, self.val+'<-', psp2d.Color(0,0,0))
		if self.modalita == 'offline':
                    self.screen.blit(self.switch[0], 0, 0, self.switch[0].width, self.switch[0].height, 156, 2, True)
                elif self.modalita == 'online':
                    self.screen.blit(self.switch[1], 0, 0, self.switch[1].width, self.switch[1].height, 156, 2, True)
		self.screen.swap()
    def AddToChron(self, parola):
        try:
            fl = open("chronology","r")
            buftemp = fl.read()
            buf = buftemp.split(",")
            fl.close()
        except:
            buf = []
        if len(buf) == 10:
            buf.pop(9)
            buf.insert(0,parola)
        else:
            buf.append(parola)
        fl = open("chronology","w")
        fl.write(",".join(buf))
        fl.close()
    def ExtractChron(self):
        fl = open("chronology","r")
        buftemp = fl.read()
        buf = buftemp.split(",")
        fl.close()
        return buf
    def TradOnline(self, server, indiceLingua):
        if server == 0:
            self.traduzioniBabel = Traduci('it.babelfish.yahoo.com/', self.val, self.lingueOnlineBabel[indiceLingua],'')
            self.box_no_trad = psp2d.Image("img/box_no_trad_babel.png")
            self.serverDaVis = 0
            self.saveTranslation(self.traduzioniBabel, 'it.babelfish.yahoo.com')
            return self.traduzioniBabel
        elif server == 1:
            self.traduzionilang = Traduci('langtolang.com', self.val, self.lingueOnlineLang[indiceLingua].split('->')[0],self.lingueOnlineLang[indiceLingua].split('->')[1])
            self.box_no_trad = psp2d.Image("img/box_no_trad_lang.png")
            self.serverDaVis = 1
            self.saveTranslation(';'.join(self.traduzionilang), 'langtolang.com')
            return self.traduzionilang
        elif server == 2:
            self.box_no_trad = psp2d.Image("img/box_no_trad_google.png")
            self.serverDaVis = 2
            self.pLang = self.lingueOnlineLang[indiceLingua].split('->')[0][0:2]
            self.sLang = self.lingueOnlineLang[indiceLingua].split('->')[1][0:2] 
            if self.lingueOnlineLang[indiceLingua].split('->')[0] == 'spanish':
                self.pLang = 'es'
            elif self.lingueOnlineLang[indiceLingua].split('->')[1] == 'spanish':
                self.sLang = 'es'
            if self.lingueOnlineLang[indiceLingua].split('->')[0] == 'german':
                self.sLang = 'de'
            elif self.lingueOnlineLang[indiceLingua].split('->')[1] == 'german':
                self.sLang = 'de'
            self.traduzioniGoogle = Traduci('google.translate.com', self.val, self.pLang+'|'+self.sLang,'')
            self.saveTranslation(self.traduzioniGoogle, 'translate.google.com')
            return self.traduzioniGoogle
    def showOnlineTrad(self, server):
        if server == 0 and self.traduzioniBabel != '':
            self.fnt.drawText(self.screen, 22, 80, 'Traslating from babelfish.yahoo.com')
            self.fnt.drawText(self.screen, 22, 105, self.traduzioniBabel)
        elif server == 1 and len(self.traduzionilang) != 0:
            self.fnt.drawText(self.screen, 22, 80, 'Traslating from langtolang.com')
            i = 0
            for trad in self.traduzionilang:
                if i < 8:
                    self.fnt.drawText(self.screen, 22, 105+10*i, trad)
                i += 1
        elif server == 2 and self.traduzioniGoogle != '':
            self.fnt.drawText(self.screen, 22, 80, 'Traslating from translate.google.com')
            self.fnt.drawText(self.screen, 22, 105, self.traduzioniGoogle)
    def saveTranslation(self, translation = '', server = ''):
        self.fl = open('translations.txt','a')
        if self.modalita == 'offline':
            self.fl.write('Mode: ' + self.modalita+'\n'+\
                          'Word: ' + self.val+'\n'+\
                          'Translation: ' + ';'.join(self.trad.traduzioni) +'\n'+\
                          '-----------------------------------------------\n')
        else:
            self.fl.write('Mode: ' + self.modalita+'\n'+\
                          'Server: ' + server+'\n'+\
                          'Word\Sentence: ' + self.val+'\n'+\
                          'Translation: ' + translation +'\n'+\
                          '-----------------------------------------------\n')
        self.fl.close()
    def Update(self): 
        while True:
            self.pad = psp2d.Controller()
            self.screen.blit(self.bg[self.qualeBg])
            self.screen.drawText(18, 50, self.val, psp2d.Color(0,0,0))
            if self.pad.cross and not self.oldpad.cross and self.qualeBg == 0:
                time.sleep(0.1)
                self.startDanzeff()
            elif self.pad.cross and not self.oldpad.cross and self.qualeBg == 1:
                if self.modalita == 'offline':
                    self.vocabolarioOff += 1
                    if self.vocabolarioOff > 4:
                        self.vocabolarioOff = 0
                    time.sleep(0.2)
            elif self.pad.square and not self.oldpad.square and self.qualeBg == 1:
                if self.modalita == 'online':
                    if self.server == 0: # 'it.babelfish.yahoo.com/'
                        self.indiceOnlineBabel -= 1
                        if self.indiceOnlineBabel < 0:
                            self.indiceOnlineBabel = 21
                    elif self.server == 1: # 'langtolang.com'
                        self.indiceOnlineLang -= 1
                        if self.indiceOnlineLang < 0:
                            self.indiceOnlineLang = 19
                    elif self.server == 2: # 'google.translate.com'
                        self.indiceOnlineGoogle -= 1
                        if self.indiceOnlineGoogle < 0:
                            self.indiceOnlineGoogle = 19
                    time.sleep(0.2)
            elif self.pad.triangle and not self.oldpad.triangle and self.qualeBg == 1:
                if self.modalita == 'online':
                    if self.server == 0: # 'it.babelfish.yahoo.com/'
                        self.indiceOnlineBabel += 1
                        if self.indiceOnlineBabel > 21:
                            self.indiceOnlineBabel = 0
                    elif self.server == 1: # 'langtolang.com'
                        self.indiceOnlineLang += 1
                        if self.indiceOnlineLang > 19:
                            self.indiceOnlineLang = 0
                    elif self.server == 2: # 'google.translate.com'
                        self.indiceOnlineGoogle += 1
                        if self.indiceOnlineGoogle > 19:
                            self.indiceOnlineGoogle = 0
                    time.sleep(0.2)
            if self.pad.cross and not self.oldpad.cross and self.qualeBg == 1:
                if self.modalita == 'online' and self.server != 0:
                    self.server -= 1
                    time.sleep(0.1)
            elif self.pad.circle and not self.oldpad.circle and self.qualeBg == 1:
                if self.modalita == 'online' and self.server != 2:
                    self.server += 1
                    time.sleep(0.1)
            if self.pad.cross and not self.oldpad.cross and self.qualeBg == 2 and self.modalita == 'offline':
                self.trad = TradOffline(self.vocabolarioOff, self.val)
                self.AddToChron(self.val)
                self.saveTranslation()
                self.tradotto = 1
                time.sleep(0.2)
            elif self.pad.cross and not self.oldpad.cross and self.qualeBg == 2 and self.modalita == 'online':
                self.AddToChron(self.val)
                if self.server == 0:
                    self.TradOnline(self.server, self.indiceOnlineBabel)
                elif self.server == 1:
                    self.TradOnline(self.server, self.indiceOnlineLang)
                elif self.server == 2:
                    self.TradOnline(self.server, self.indiceOnlineGoogle)
                self.tradotto = 2
            if self.pad.cross and not self.oldpad.cross and self.qualeBg == 3:
                self.showChron = True
            if self.qualeBg == 1:
                if self.modalita == 'offline':
                    self.screen.drawText(216, 255, self.vocabolariOff[self.vocabolarioOff], psp2d.Color(128,128,128))
                elif self.modalita == 'online':
                    self.screen.blit(self.bgLenteOn)
                    self.screen.drawText(18, 50, self.val, psp2d.Color(0,0,0))
                    if self.server == 0: # 'it.babelfish.yahoo.com/'
                        self.screen.drawText(80, 262, 'babelfish.yahoo.com',psp2d.Color(128,128,128))
                        self.daVis = self.lingueOnlineBabel[self.indiceOnlineBabel]
                        self.daVis1 = self.daVis.replace(self.daVis[0:2],self.visualizzazioniOnlineBabel[self.daVis[0:2]])
                        self.daVis2 = self.daVis.replace(self.daVis[3:5],self.visualizzazioniOnlineBabel[self.daVis[3:5]])
                        self.screen.drawText(140, 248, self.daVis1[0:len(self.daVis1)-3] + '->'+ self.daVis2[3:len(self.daVis1)],psp2d.Color(128,128,128))
                    elif self.server == 1: # 'langtolang.com/'
                        self.screen.drawText(80, 262, 'langtolang.com (only words)',psp2d.Color(128,128,128))
                        self.screen.drawText(140, 248, self.lingueOnlineLang[self.indiceOnlineLang],psp2d.Color(128,128,128))
                    elif self.server == 2: # 'google.translate.com/'
                        self.screen.drawText(80, 262, 'translate.google.com',psp2d.Color(128,128,128))
                        self.screen.drawText(140, 248, self.lingueOnlineLang[self.indiceOnlineGoogle],psp2d.Color(128,128,128))
            if self.pad.left and self.qualeBg != 0:
                self.qualeBg -= 1
                time.sleep(0.2)
            elif self.pad.right and self.qualeBg != 3:
                self.qualeBg += 1
                time.sleep(0.2)
            if self.tradotto == 1: ## Tradotto offline. Visualizzo traduzioni.
                self.screen.blit(self.box_trad_off, 0, 0, self.box_trad_off.width, self.box_trad_off.height, 15, 73, True)
                try:
                    self.screen.drawText(87, 95, self.trad.traduzioni[1], psp2d.Color(128,128,128))
                    self.screen.drawText(87, 95+15, self.trad.traduzioni[0], psp2d.Color(128,128,128))
                    self.screen.drawText(87, 95+30, self.trad.traduzioni[2], psp2d.Color(128,128,128))
                    self.screen.drawText(87, 95+45-2, self.trad.traduzioni[3], psp2d.Color(128,128,128))
                    self.screen.drawText(87, 95+60-3, self.trad.traduzioni[4][0:len(self.trad.traduzioni[4])-2], psp2d.Color(128,128,128))
                except:
                    pass
            elif self.tradotto == 2: ## Tradotto online. Visualizzo traduzioni.
                self.screen.blit(self.box_no_trad, 0, 0, self.box_no_trad.width, self.box_no_trad.height, 15, 73, True)
                self.showOnlineTrad(self.serverDaVis) 
            if self.pad.r and pspnet.wlanIsPowered() == True and pspnet.wlanSwitchState() == True:
                time.sleep(0.2)
                self.connecting = True
                connect()
            elif self.pad.l:
                time.sleep(0.2)
                self.connecting = False
                pspnet.disconnectAPCTL()
                self.modalita = 'offline'
            if self.connecting == True:
                try:
                    ip = pspnet.getIP()
                    self.modalita = 'online'
                except:
                    self.screen.blit(self.box_connecting, 0, 0, self.box_connecting.width, self.box_connecting.height, 480/2-307/2, 60, True)
                    self.fnt.drawText(self.screen,97,169+35,'Connection: '+pspnet.enumConfigs()[0][1])
            if self.showChron == True:
                self.screen.blit(self.box_chron, 0, 0, self.box_chron.width, self.box_chron.height, 480/2-307/2, 40, True)
                i = 1
                ex = self.ExtractChron()
                for c in ex:
                    if len(c) < 40:
                        self.fnt.drawText(self.screen,100,65+15*i,"- "+c.upper())
                    else:
                        self.fnt.drawText(self.screen,100,65+15*i,"- "+c.upper()[0:34]+'...')
                    i += 1
                if self.pad.cross:
                    self.showChron = False
            if self.modalita == 'offline':
                self.screen.blit(self.switch[0], 0, 0, self.switch[0].width, self.switch[0].height, 156, 2, True)
            elif self.modalita == 'online':
                self.screen.blit(self.switch[1], 0, 0, self.switch[1].width, self.switch[1].height, 156, 2, True)
        
            #self.screen.drawText(10, 10, str(self.server), psp2d.Color(128,128,128)) #debug mode
            self.pad = self.oldpad
            self.screen.swap()
