import pspnet, psp2d, urllib, thread,time
from pspos import freemem
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.lente_sel_on = psp2d.Image("img/lente_sel_on.png")
        self.qualeBg = 0
        self.fnt = psp2d.Font("img/font.png")
        self.fnt1 = psp2d.Font("img/font1.png")
        self.textbar = psp2d.Image("img/textbar.png")
        self.box_trad_off = psp2d.Image("img/box_trad_off.png")
        self.box_no_trad = psp2d.Image("img/box_no_trad.png")
        self.box_connecting = psp2d.Image("img/box_conn.png")
        self.box_chron = psp2d.Image("img/box_chron.png")
        self.switch = [psp2d.Image("img/off.png"), psp2d.Image("img/on.png")]
        self.freccia = [psp2d.Image('img/down.png'), psp2d.Image('img/up.png')]
        self.val = '' # For the Danzeff library.
        self.valOn = ''
        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.mostraOn = 0 # Quale lingua di traduzione mostrare online.
        self.onMostraDa = 0
        self.connecting = False
        self.trad = None
        self.showChron = False
        self.vocabolari = {0:"English",1:"Italiano",2:"Francais",3:"Deutsche",4:"Espanol"}
        self.vocabolario = 0      # Offline
        self.linguatradOnline = 0 # Online
        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.fnt.drawText(self.screen, 25, 83, 'Traslating from '+self.vocabolari[self.vocabolario]+' to '+self.vocabolari[self.linguatradOnline])
                    try:
                            self.mostraTradOnline()
                    except:
                        pass
		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:
				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[0].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 TraduciOnline(self):
        self.valOn = self.val
        self.AddToChron(self.val)
        self.tradotto = 2
        if self.mostraOn == 0:
            self.tradeng = Traduci(self.vocabolario,'english', self.val)
            self.linguatradOnline = 0
        elif self.mostraOn == 1:
            self.tradita = Traduci(self.vocabolario,'italian', self.val)
            self.linguatradOnline = 1
        elif self.mostraOn == 2:
            self.tradfrench = Traduci(self.vocabolario,'french', self.val)
            self.linguatradOnline = 2
        elif self.mostraOn == 3:
            self.tradgerman = Traduci(self.vocabolario,'german', self.val)
            self.linguatradOnline = 3
        elif self.mostraOn == 4:
            self.tradspa = Traduci(self.vocabolario,'spanish', self.val)
            self.linguatradOnline = 4
    def mostraTradOnline(self):
        self.visualizzte = 0
        if self.onMostraDa > 0:
            self.screen.blit(self.freccia[1], 0, 0, self.freccia[1].width, self.freccia[1].height, 433, 80, True)
        if self.linguatradOnline == 0: # Mostro traduzioni english:
            if self.onMostraDa <= len(self.tradeng)-8:
                self.screen.blit(self.freccia[0], 0, 0, self.freccia[0].width, self.freccia[1].height, 433, 169-10, True)
            if self.pad.down and self.onMostraDa <= len(self.tradeng)-8:
                time.sleep(0.2)
                self.onMostraDa += 1
            elif self.pad.up and self.onMostraDa > 0:
                time.sleep(0.2)
                self.onMostraDa -= 1
            if len(self.tradeng) != 0:
                for i in range(self.onMostraDa, len(self.tradeng)):
                    if self.visualizzte < 7:
                        self.fnt.drawText(self.screen, 25, 97 + 12*self.visualizzte, self.valOn+':       '+self.tradeng[i])
                        self.visualizzte += 1
            else:
                self.fnt.drawText(self.screen, 25, 97+12, '- No Translation Found -')
        elif self.linguatradOnline == 1: # Mostro traduzioni italian:
            if self.onMostraDa <= len(self.tradita)-8:
                self.screen.blit(self.freccia[0], 0, 0, self.freccia[0].width, self.freccia[1].height, 433, 169-10, True)
            if self.pad.down and self.onMostraDa <= len(self.tradita)-8:
                time.sleep(0.2)
                self.onMostraDa += 1
            elif self.pad.up and self.onMostraDa > 0:
                time.sleep(0.2)
                self.onMostraDa -= 1
            if len(self.tradita) != 0:
                for i in range(self.onMostraDa, len(self.tradita)):
                    if self.visualizzte < 7:
                        self.fnt.drawText(self.screen, 25, 97 + 12*self.visualizzte, self.valOn+':       '+self.tradita[i])
                        self.visualizzte += 1
            else:
                self.fnt.drawText(self.screen, 25, 97+12, '- No Translation Found -')
        elif self.linguatradOnline == 2: # Mostro traduzioni french:
            if self.onMostraDa <= len(self.tradfrench)-8:
                self.screen.blit(self.freccia[0], 0, 0, self.freccia[0].width, self.freccia[1].height, 433, 169-10, True)
            if self.pad.down and self.onMostraDa <= len(self.tradfrench)-8:
                time.sleep(0.2)
                self.onMostraDa += 1
            elif self.pad.up and self.onMostraDa > 0:
                time.sleep(0.2)
                self.onMostraDa -= 1
            if len(self.tradfrench) != 0:
                for i in range(self.onMostraDa, len(self.tradfrench)):
                    if self.visualizzte < 7:
                        self.fnt.drawText(self.screen, 25, 97 + 12*self.visualizzte, self.valOn+':       '+self.tradfrench[i])
                        self.visualizzte += 1
            else:
                self.fnt.drawText(self.screen, 25, 97+12, '- No Translation Found -')
        elif self.linguatradOnline == 3: # Mostro traduzioni german:
            if self.onMostraDa <= len(self.tradgerman)-8:
                self.screen.blit(self.freccia[0], 0, 0, self.freccia[0].width, self.freccia[1].height, 433, 169-10, True)
            if self.pad.down and self.onMostraDa <= len(self.tradgerman)-8:
                time.sleep(0.2)
                self.onMostraDa += 1
            elif self.pad.up and self.onMostraDa > 0:
                time.sleep(0.2)
                self.onMostraDa -= 1
            if len(self.tradgerman) != 0:
                for i in range(self.onMostraDa, len(self.tradgerman)):
                    if self.visualizzte < 7:
                        self.fnt.drawText(self.screen, 25, 97 + 12*self.visualizzte, self.valOn+':       '+self.tradgerman[i])
                        self.visualizzte += 1
            else:
                self.fnt.drawText(self.screen, 25, 97+12, '- No Translation Found -')
        elif self.linguatradOnline == 4: # Mostro traduzioni spanish:
            if self.onMostraDa <= len(self.tradspa)-8:
                self.screen.blit(self.freccia[0], 0, 0, self.freccia[0].width, self.freccia[1].height, 433, 169-10, True)
            if self.pad.down and self.onMostraDa <= len(self.tradspa)-8:
                time.sleep(0.2)
                self.onMostraDa += 1
            elif self.pad.up and self.onMostraDa > 0:
                time.sleep(0.2)
                self.onMostraDa -= 1
            if len(self.tradspa) != 0:
                for i in range(self.onMostraDa, len(self.tradspa)):
                    if self.visualizzte < 7:
                        self.fnt.drawText(self.screen, 25, 97 + 12*self.visualizzte, self.valOn+':       '+self.tradspa[i])
                        self.visualizzte += 1
            else:
                self.fnt.drawText(self.screen, 25, 97+12, '- No Translation Found -')
    def Update(self):
        while True:
            self.pad = psp2d.Controller()
            self.screen.blit(self.bg[self.qualeBg])
            if self.qualeBg == 1 and self.modalita == 'online':
                self.screen.blit(self.lente_sel_on)
            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:
                self.startDanzeff()
            elif self.pad.cross and not self.oldpad.cross and self.qualeBg == 1:
                self.vocabolario += 1
                if self.vocabolario > 4:
                    self.vocabolario = 0
                time.sleep(0.2)
            elif self.pad.circle and not self.oldpad.circle and self.qualeBg == 1 and self.modalita == 'online':
                self.mostraOn += 1
                if self.mostraOn > 4:
                    self.mostraOn = 0
                time.sleep(0.2)
            if self.pad.cross and not self.oldpad.cross and self.qualeBg == 2 and self.modalita == 'offline':
                self.trad = TradOffline(self.vocabolario, self.val)
                self.AddToChron(self.val)
                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.onMostraDa = 0
                self.TraduciOnline()
            if self.pad.cross and not self.oldpad.cross and self.qualeBg == 3:
                self.showChron = True
            if self.qualeBg == 1 and self.modalita == 'offline':
                self.screen.drawText(216, 255, self.vocabolari[self.vocabolario], psp2d.Color(128,128,128))
            elif self.qualeBg == 1 and self.modalita == 'online':
                self.screen.drawText(150+45, 248, self.vocabolari[self.vocabolario], psp2d.Color(128,128,128))
                self.screen.drawText(150+45, 260, self.vocabolari[self.mostraOn], 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:
                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.fnt.drawText(self.screen, 25, 83, 'Traslating from '+self.vocabolari[self.vocabolario]+' to '+self.vocabolari[self.linguatradOnline])
                try:
                    self.mostraTradOnline()
                except:
                    pass
            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.mostraOn = 0
                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)
            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:
                    self.fnt.drawText(self.screen,100,65+15*i,"- "+c.upper())
                    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(freemem() / 1024) + 'kb', psp2d.Color(128,128,128)) Shows the free mem
            self.pad = self.oldpad
            self.screen.swap()
