import display
import buttons
import random
import math
import audio
import mch22
import nvs
import sys
import time
import network
import socket

import uasyncio as asyncio

#APP_PATH = "/".join(__file__.split("/")[:-1])
#sys.path.append(APP_PATH)
#print(APP_PATH)

import tamagotchi



background_color = 0xcc9fde
foreground_color = 0x776e65
info_font = "roboto_regular12"
title_font = "roboto_black22"
small_font = "fairlight8"
board_dim = 200
size = 4

display_width = display.width()
display_height = display.height()
print("detected display: " + str(display_width) + "x" + str(display_height))


# Helper to detect uasyncio v3
IS_UASYNCIO_V3 = hasattr(asyncio, "__version__") and asyncio.__version__ >= (3,)

SERVER_SSID = 'tamagotchi'  # max 32 characters
SERVER_IP = '192.168.4.1'
SERVER_SUBNET = '255.255.255.0'

nickname = nvs.nvs_getstr("owner","nickname")
#APP_PATH = "/".join(__file__.split("/")[:-1])
APP_PATH = "/apps/python/tamagotchi"
sys.path.append(APP_PATH)

print ("starting tamagotchi")
#print (APP_PATH)

# def reboot(pressed):
#     if pressed:
#         mch22.exit_python()
# buttons.attach(buttons.BTN_HOME, reboot)

#------------------------------------------------------------------------

LOOK_R = '( O_o)'
LOOK_L = '(o_O )'
LOOK_R_HAPPY = '( O>__<O )'
LOOK_L_HAPPY = '( ó_O )'
SLEEP = '(-__-)'
SLEEP2 = '(=__=)'
BORED = '(-__-)'
INTENSE = '(@__@)'
ANGRY = "(>_<')"
FRIEND = '(*^_^*)'
DEBUG = '(#__#)'
UPLOAD = '(1__0)'
UPLOAD1 = '(1__1)'
UPLOAD2 = '(0__1)'
HAPPY = '(^_^)'
LONELY = '(;_;)'
SAD = '(T_T )'
BROKEN = '(X__X)'
BORED = '(-__-)'
INTENSE = '(°===°)'
COOL = '(-O_O )'
HUNGRY = '(#___#)'
AWAKE = '(◕‿‿◕)'
GRATEFUL = '(^‿‿^)'
EXCITED = '(ᵔ◡◡ᵔ)'
MOTIVATED = '(☼‿‿☼)'
DEMOTIVATED = '(≖__≖)'
SMART = '(✜‿‿✜)'

class Tamagotchi:
    def __init__(self, name):
        print("Instanciamos el tamagotchi " + name)
        self.name = name
        self.hunger = 0    # disminuye con la comida, aumenta con el tiempo
        self.happiness = 0  # disminuye si no tienen interaccion con usuario o con otros tamagotchis
        self.health = 3    # disminyue cuando el hambre esta alto y aleatoriamente y con cierta comida
        self.energy = 5      # disminuye con la actividad. aumenta con el sueño y cierta comida
        self.age = 0     # aumenta con el tiempo
        self.carita = LOOK_R
        self.frase = ""
        self.meal_grouth_delay = 10
        self.frase_change_delay = 10
        self.meals = [3,3,3]  #sana verduritas, intermedia, carne y mala hamburguesa
        self.UIstatus = "menu_principal"
        self.status = 'happy'
        self.evolucion = 1
        # status: happy, sad, hungry, ungry, broken, dead
        # evolucion: huevo, bebe, niño, joven, adulto, viejo (0-5)
        self.x= 80
        self.y= 240-60-12-10
        
        self.last_time = 0
        self.last_meal_grouth = time.time()
        self.last_change_frase = 0
        
        self.sad_phrases = [
            "Estoy muy triste...", "¿Por que no juegas conmigo?", "Necesito un poco de diversion.",
            "Hoy no es un buen dia...", "Me siento solo.", "Nada parece alegrarme...",
            "¿Es que a nadie le importo?", "Estoy aburrido...", "Nada tiene sentido ahora...",
            "Estoy muy deprimido.", "Mi corazon esta hecho trizas.", "¿Por que me siento tan solo?",
            "Todo es tan gris...", "No tengo animos para nada.", "La tristeza me consume...",
            "¿Alguien me quiere?", "No hay alegria en mi vida.", "Nada me hace sonreir...",
            "Me siento olvidado...", "Estoy en un hoyo emocional."
        ]
        self.broken_phrases = [
            "No me siento bien...", "¡Estoy enfermo!", "Creo que necesito un medico.",
            "Siento que algo no esta bien...", "Estoy muy debil.", "Me duele todo...",
            "No puedo moverme bien.", "Cada movimiento me duele.", "¿Por que me siento asi?",
            "Mi salud esta decayendo.", "Estoy roto por dentro y por fuera.", "No tengo fuerzas para nada.",
            "Estoy muy enfermo...", "Mi energia se esta agotando.", "¿Es este el fin?",
            "Mi cuerpo no responde...", "Estoy demasiado debil para continuar.", "Necesito ayuda, urgentemente.",
            "Me siento peor cada dia...", "Mi salud es un desastre."
        ]
        self.happy_phrases = [
            "¡Me siento genial!", "Todo esta bien.", "Estoy contento.",
            "Hoy es un gran dia.", "Estoy lleno de energia.", "Nada puede detenerme.",
            "Me siento increible.", "Todo es perfecto.", "Soy feliz.",
            "Nada me preocupa.", "¡Estoy en la cima del mundo!", "La vida es maravillosa.",
            "No puedo dejar de sonreir.", "Estoy muy alegre.", "Todo es tan hermoso.",
            "Me siento afortunado.", "Estoy muy emocionado por todo.", "La felicidad me invade.",
            "Hoy es mi dia.", "Estoy lleno de alegria."
        ]
        self.hungry_phrases = [
            "¡Tengo mucha hambre!", "¡Dame de comer!", "¡Me estoy muriendo de hambre!",
            "¡No puedo aguantar mas el hambre!", "Necesito comida, ¡ya!", "¡Por favor, alimenta a este pobre ser!",
            "¿No ves que estoy hambriento?", "No puedo pensar con el estomago vacio...", "Me siento debil... ¿Hay comida?",
            "¡Un bocado, por favor!", "La comida es mi vida... y mi vida se esta acabando.", "¡Alimentame!",
            "¡Estoy desfalleciendo!", "Necesito comida, ¡y la necesito ahora!", "¿Es mucho pedir un poco de comida?",
            "¿Acaso he hecho algo para no merecer comida?", "¡Ayudame, tengo hambre!", "No recuerdo la ultima vez que comi...",
            "¡Mis tripas estan rugiendo!", "¿Donde esta mi comida?"
        ]

        

    def feed(self, tipo_comida):
     if self.meals[tipo_comida] >0:
      self.meals[tipo_comida] -=  1
      if tipo_comida == 0: #comida sana
       self.hunger -= 0.5
       self.health += 0.2
      elif tipo_comida == 1:
       self.hunger -= 0.7 #comida media
      elif tipo_comida == 2: #comida sana
       self.hunger -= 1
       self.health -= 0.4
    
      if self.hunger < 0: self.hunger = 0
      print(f'{self.name} ha sido alimentado.')
     else:
      print("no hay comida suficiente")  
      self.frase = "no hay comida suficiente...."
     
    
    def play(self,juego, choice):
     preguntas = [
       {"pregunta": "El sol es una estrella.", "respuesta": True},
       {"pregunta": "El agua hierve a 50 grados Celsius.", "respuesta": False},
       {"pregunta": "Los humanos tienen 206 huesos en el cuerpo.", "respuesta": True},
       {"pregunta": "Las ballenas son peces.", "respuesta": False},
       {"pregunta": "La Tierra es mas pequena que Marte.", "respuesta": False},
       {"pregunta": "El plomo es un metal.", "respuesta": True},
       {"pregunta": "El ADN se encuentra en el núcleo de las células.", "respuesta": True},
       {"pregunta": "La capital de Australia es Sydney.", "respuesta": False},
       {"pregunta": "El hielo es mas denso que el agua liquida.", "respuesta": False},
       {"pregunta": "La luz viaja mas rapido que el sonido.", "respuesta": True}
   ]
     
     
     if juego == "true/lie":
      #selecciona una pregunta y marca la respuesta correcta
      pregunta = random.choice(preguntas)
      self.frase = pregunta['pregunta']
      if (choice == 1 and pregunta['respuesta'] == True):
       self.frase = "muy bien, las repuesta era correcta!!!!"      
      elif (choice == 2 and pregunta['respuesta'] == False):
       self.frase = "muy bien, las frase era falsa!!!!"      
      elif (choice == 1 and pregunta['respuesta'] == False):
       self.frase = "Oups, las frase era falsa!!!!"      
      elif (choice == 2 and pregunta['respuesta'] == True):
       self.frase = "Oups, las frase era correcta!!!!"      
       
      self.happiness -= 0.2

        
    def heal(self):
        self.health += 1
        if self.health > 5:
            self.health = 5
        #print(f'{self.name} ha recibido medicina.')

    def clean(self):
        print(f'{self.name} ha sido limpiado.')

    def update(self):
    #segun el estado evoluciono sus constantes
    # status: happy, sad, hungry, ungry, broken, dead
      if self.status != 'dead':
        self.age += 1
        if self.status == 'happy':
         self.hunger += 0.1
         self.happiness += 0.1
         self.health -= 0.1
        elif self.status == 'sad':
         self.hunger += 0.2
         self.happiness += 0.3
         self.health -= 0.2
        elif self.status == 'hungry':
         self.hunger += 0.1
         self.happiness += 0.6
         self.health -= 0.8
        elif self.status == 'ungry':
         self.hunger += 0.1
         self.happiness += 0.6
         self.health -= 0.1         
        elif self.status == 'broken':
         self.hunger += 0.1
         self.happiness += 0.001
         self.health -= 0.01
         
        #limites
        if self.hunger > 5: self.hunger = 5
        if self.happiness > 5: self.happiness = 5
        if self.health <0: self.health = 0
        
        
        
        # actualizo carita, status
        self.actualiza_estado()

        # actualizo frase
        if time.time() - self.last_change_frase  > self.frase_change_delay:
         if self.status   == 'hungry':  self.frase = random.choice(self.hungry_phrases)
         elif self.status == 'sad':   self.frase = random.choice(self.sad_phrases)
         elif self.status == 'broken':  self.frase = random.choice(self.broken_phrases)
         elif self.status == 'happy':  self.frase = random.choice(self.happy_phrases)
         self.last_change_frase = time.time()
            
        # la comida va creciendo
        if time.time() - self.last_meal_grouth > self.meal_grouth_delay:
         self.last_meal_grouth = time.time()
         self.meals[0] = min (self.meals[0], 3)
         self.meals[1] = min (self.meals[1], 3)
         self.meals[2] = min (self.meals[2], 3)         
        
        # evoluciono al tmagotchi
        self.evoluciona()


    def evoluciona(self):
     # status: happy, sad, hungry, ungry, broken, dead
     # evolucion: huevo, bebe, niño, adulto, viejo (0-4)
     last_evolucion = self.evolucion
     
     if self.age >= 50:   #viejo
      self.evolucion = 4 
     elif self.age >= 25:  #adulto
      self.evolucion = 3
     elif self.age >= 15:  #niño
      self.evolucion = 2
     elif self.age >= 3:  #bebe
      self.evolucion = 1
      if last_evolucion != self.evolucion:
       self.status = 'happy'
       self.frase = "acaba de nacer " + self.name + "\n Bienvenido al mundo!" 
     else:         #huevo
      self.evolucion = 0             


    def actualiza_estado(self):
     # status: happy, sad, hungry, ungry, broken, dead
     # evolucion: huevo, bebe, niño, adulto, viejo (0-4)
     last_status = self.status
     if self.health != 'dead':
      if self.health <= 0: 
       self.muerte()
      elif self.hunger > 4:
       self.status = 'hungry'
       self.carita = random.choice([HUNGRY])
      elif self.happiness <= 2:
       self.status = 'ungry'
       self.carita = random.choice([SAD, BORED, LONELY,ANGRY])
      elif self.health <= 2:
       self.status = 'broken'
       self.carita = random.choice([INTENSE])
      else:
       self.status = 'happy'
       self.carita = random.choice([LOOK_R,LOOK_L,LOOK_R_HAPPY, LOOK_L_HAPPY, FRIEND, COOL])
       
       
     #cuando es muy mayor, aleatoriamente, puede morir.
     if self.age >= 90: 
      if random.choice([1-100]) > 80:
          self.muerte()
     
        
        
     if last_status != self.status:
      self.last_change_frase = 0
      self.actualiza_estado()


    def muerte(self):
          self.status = 'dead'
          #170x320
          self.x = random.randint(160, 260)
          self.y += random.randint(-4, 4)
          self.frase = "RIP. " + self.name + "\n Descanse en paz."









#----------------------------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------------------------
          


class MyApp:
    async def start(self):
        #variables
        self.debug = True
        self.mascotas=[]
        
        
        # Get the event loop
        loop = asyncio.get_event_loop()

        # Add global exception handler
        if IS_UASYNCIO_V3:
            loop.set_exception_handler(_handle_exception)

        
        #setup de botones
        #self.buttons = tft_buttons.Buttons()
            
            
            
        #setup de TFT
        #tft.init()
            
        index = 3
        display.drawFill(background_color)
        display.drawText(10, index, "LCD started...", foreground_color, info_font)
        index += ( 12 + 3)
        #display.drawText(10, 3+12+3, "tamagotchi", foreground_color, info_font)
        display.flush()
 
#         self.miCmd1 = menu.cmd(tft)
#         self.miCmd1.cmdClr()
#         self.miCmd1.cmdPrint("LCD started...")
#         tft.show()
        time.sleep(1)
        
        # Crear una instancia de Tamagotchi
        display.drawText(10, index, "Creamos Instancia de tamagotchi...", foreground_color, info_font)
        index += ( 12 + 3)
        display.flush()
        time.sleep(1)
        #self.miCmd1.cmdPrint("Creamos Instancia de tamagotchi...")
        #tft.show()
        self.mi_mascota = tamagotchi.Tamagotchi(random.choice(["Santiago", "Mateo", "Sebastian", "Valentina", "Sofia", "Camila",
                                                    "Isabella", "Mariana", "Gabriel", "Lucas", "Martin", "Victoria",
                                                    "Daniel", "Lucia", "Tomas", "Alejandro", "Emilia", "Samuel", "Juan",
                                                    "Miguel", "Paula", "Jose", "Antonia", "Renata", "Luna", "Andres",
                                                    "Manuel", "David", "Carlos", "Angel", "Carolina", "Gonzalo", "Carmen",
                                                    "Luis", "Elena", "Sara", "Julia", "Pablo", "Felipe", "Jorge", "Elisa",
                                                    "Ricardo", "Fernando", "Catalina", "Simon", "Victoria", "Alvaro", 
                                                    "Nicolas", "Santiago", "Laura", "Monica", "Fabian", "Guillermo", 
                                                    "Sergio", "Francisco", "Marcela", "Rafael", "Natalia", "Angela", 
                                                    "Raul", "Claudia", "Hugo", "Esteban", "Lorena", "Beatriz", "Ivan", 
                                                    "Olga", "Ramon", "Patricia", "Isabel", "Victor", "Teresa", "German", 
                                                    "Silvia", "Oscar", "Marta", "Marcos", "Liliana", "Adriana", "Diana", 
                                                    "Jacobo", "Alberto", "Olivia", "Eduardo", "Alicia", "Enrique", "Clara", 
                                                    "Benjamin", "Irene", "Hector", "Veronica", "Mario", "Daniela", 
                                                    "Javier", "Rosa", "Santos", "Sonia", "Cristina", "Rodrigo", "Lucia"]))
        
        
        # Iniciar punto de acceso y servidor web
        display.drawText(10, index, "creando AP y servidor web...", foreground_color, info_font)
        index += ( 12 + 3)
        display.flush()
        time.sleep(1)
        #self.miCmd1.cmdPrint("creando AP y servidor web...")
        # Start the wifi AP
        self.init_access_point(SERVER_SSID)

        # Create the server and add task to event loop
        async def handle_http_connection_closure(reader, writer):
            await self.handle_http_connection(reader, writer, self.mi_mascota)
        
        server = asyncio.start_server(handle_http_connection_closure, "0.0.0.0", 80)
        loop.create_task(server)
        #start_web_server(mi_mascota)
        #_thread.start_new_thread(start_web_server, (mi_mascota,))
        
        # Start the DNS server task
        loop.create_task(self.run_dns_server())
        
        #tft.show()
        time.sleep(1)
        
        # finish
#         self.miCmd1.cmdClr()
#         tft.show()
        display.drawFill(background_color)
        display.flush()
        
        
        #------------ creamos el menu y los CMDs -------------------
        
        #menuItemsList,fg, bg,length, startX, startY, cabecera, tituloCabecera
#         self.mi_menu = menu.Menu(tft, ["clean","feed","play","heal"], s3lcd.WHITE, s3lcd.BLACK, 20, 0, 0,               True, "MENU")
#         
#         self.rotary = rotary_irq_esp.RotaryIRQ(pin_num_clk=2,
#               pin_num_dt=1,
#               min_val=0,
#               max_val=len(self.mi_menu.menuItemsList),
#               reverse=False,
#               range_mode=rotary_irq_esp.RotaryIRQ.RANGE_WRAP)
#         self.lastButtonValue = 1

#         if (self.debug == True):
#             self.miCmd = menu.cmd(tft, s3lcd.WHITE, s3lcd.BLACK, 40, 0, 20, 20, True, "STATS")
        #frase de dialogo del tamagotchi
        #def __init__(self,  tft, fg=s3lcd.WHITE, bg=s3lcd.BLACK, startX=0, startY=0, maxX=40, maxY=40, cabecera=False, tituloCabecera="",font=fontSmall):
        
#         self.fraseCmd = menu.cmd(tft, s3lcd.WHITE, s3lcd.BLACK, 0, 19, 80, 1, False, "")  


        # Start looping forever
        print('Looping forever...')
        loop.create_task(self.mainLoop())
        loop.run_forever()

    async def mainLoop(self):
        last_tama_time = time.time()
#         last_rotary_val = self.rotary.value()
        while True:
            try:
                #avanza el tiempo y actualiza tama cada 2 segundos
                actual_tama_time = time.time()
                if(actual_tama_time - last_tama_time >= 2):
                    last_tama_time=actual_tama_time
                    self.mi_mascota.update()
                    self.actualizaPantalla()
                    # gc.collect()
                
                #si esta muerto, lo meto en el array de muertos y creo otro
                if (self.mi_mascota.status == 'dead'):
                    self.creaTamagotchi()
                
                
                #si detecto movimiento del rotary, actualizo pantalla
#                 new_rotary_val = self.rotary.value()
#                 if (new_rotary_val != last_rotary_val):
#                     self.mi_menu.menuPrint(new_rotary_val)
#                     tft.show()
#                     last_rotary_val = new_rotary_val
                    
                    



                    
                #----------------check innput
#                 if self.buttons.left.value() == 0:
#                     if self.lastButtonValue == 1:
#                         print("executing: " + self.mi_menu.menuItemsList[new_rotary_val-1])
#                         #------
#                         if self.mi_menu.getItem(new_rotary_val)[:6] == "carrot":
#                             self.mi_mascota.feed(0)
#                             self.mi_menu.updateMenu(["clean","feed","play","heal"])
#                         elif self.mi_menu.getItem(new_rotary_val)[:5] == "carne":
#                             self.mi_mascota.feed(1)
#                             self.mi_menu.updateMenu(["clean","feed","play","heal"])
#                         elif self.mi_menu.getItem(new_rotary_val)[:7] == "burguer":
#                             self.mi_mascota.feed(2)
#                             self.mi_menu.updateMenu(["clean","feed","play","heal"])
#                         elif self.mi_menu.getItem(new_rotary_val) == "feed":
#                             self.mi_menu.updateMenu(["carrot:" + str(self.mi_mascota.meals[0]),
#                                                      "carne:" + str(self.mi_mascota.meals[1]),
#                                                      "burguer:" + str(self.mi_mascota.meals[2]) ])
# 
#                             
#                         elif self.mi_menu.getItem(new_rotary_val) == "play":
#                             self.mi_mascota.frase = "Wow genial! a que quieres jugar???"
#                             self.mi_menu.updateMenu(["cucu","piedra","true/lie"])
#                         elif self.mi_menu.getItem(new_rotary_val) == "true":
#                             self.mi_mascota.play("true/lie",1)
#                             self.mi_menu.updateMenu(["feed","heal","play"])
#                         elif self.mi_menu.getItem(new_rotary_val) == "lie":
#                             self.mi_mascota.play("true/lie",2)
#                             self.mi_menu.updateMenu(["feed","heal","play"])
#                         elif self.mi_menu.getItem(new_rotary_val) == "true/lie":
#                             self.mi_mascota.play("true/lie",0)
#                             self.mi_menu.updateMenu(["true","lie","cancel"])
#                         elif self.mi_menu.getItem(new_rotary_val) == "cancel":
#                             self.mi_menu.updateMenu(["true","lie","cancel"]) 
#                             self.mi_menu.updateMenu(["feed","heal","play"])
#                         
#                         elif self.mi_menu.getItem(new_rotary_val) == "heal":
#                             self.mi_mascota.heal()
#                         elif self.mi_menu.getItem(new_rotary_val) == "clean":
#                             self.mi_mascota.clean()                        
#                         #----
#                         self.lastButtonValue = 0
#                         self.actualizaPantalla()
#                 else:
#                     self.lastButtonValue = 1
                
                # Ceder el control al scheduler de asyncio
                await asyncio.sleep(0)

            except Exception as e:
                print("Main Loop error :", e)
                await asyncio.sleep_ms(3000)


    def creaTamagotchi(self):
        self.mascotas.append(self.mi_mascota)
        self.mi_mascota = tamagotchi.Tamagotchi(random.choice(["Santiago", "Mateo", "Sebastian", "Valentina", "Sofia", "Camila",
                                                    "Isabella", "Mariana", "Gabriel", "Lucas", "Martin", "Victoria",
                                                    "Daniel", "Lucia", "Tomas", "Alejandro", "Emilia", "Samuel", "Juan",
                                                    "Miguel", "Paula", "Jose", "Antonia", "Renata", "Luna", "Andres",
                                                    "Manuel", "David", "Carlos", "Angel", "Carolina", "Gonzalo", "Carmen",
                                                    "Luis", "Elena", "Sara", "Julia", "Pablo", "Felipe", "Jorge", "Elisa",
                                                    "Ricardo", "Fernando", "Catalina", "Simon", "Victoria", "Alvaro", 
                                                    "Nicolas", "Santiago", "Laura", "Monica", "Fabian", "Guillermo", 
                                                    "Sergio", "Francisco", "Marcela", "Rafael", "Natalia", "Angela", 
                                                    "Raul", "Claudia", "Hugo", "Esteban", "Lorena", "Beatriz", "Ivan", 
                                                    "Olga", "Ramon", "Patricia", "Isabel", "Victor", "Teresa", "German", 
                                                    "Silvia", "Oscar", "Marta", "Marcos", "Liliana", "Adriana", "Diana", 
                                                    "Jacobo", "Alberto", "Olivia", "Eduardo", "Alicia", "Enrique", "Clara", 
                                                    "Benjamin", "Irene", "Hector", "Veronica", "Mario", "Daniela", 
                                                    "Javier", "Rosa", "Santos", "Sonia", "Cristina", "Rodrigo", "Lucia"]))
 
    
    def printBadgeName(self):
#         nick_w = display.getTextWidth(nickname)
#         nick_h = display.getTextHeight(nickname)
# 
#         scaling = 1.15 * display_width // nick_w
# 
#         display.translate( display_width // 2 , display_height // 2 - 20)
#         display.rotate(0.15)
#         display.scale(scaling,scaling)
#         display.drawText( -nick_w // 2, -nick_h // 2, nickname)

        display.drawRect(0,0,320,66,True, 0x000000)

        
        display.drawPng(0, 0, "%s/%s" % (APP_PATH, "fondo_why.png"))
        textW=display.getTextWidth(nickname,"permanentmarker36")
        display.drawText(int(320/2-textW/2), 10, nickname, 0xffffff, "permanentmarker36")
        display.drawLine(0,67,320,67, 0x686868)

    def actualizaPantalla(self):
#         self.miCmd.cmdClr()
        display.drawFill(background_color)
        #----------------pintamos la parte izq
#         val_new = self.rotary.value()
#         self.mi_menu.menuPrint(val_new)

        #----------------
        self.printBadgeName()

        #----------------pintamos la parte derecha
        if (self.debug == True):
            y = 15*5
            x = 200
            display.drawText(x, y, "age:      "+ str(self.mi_mascota.age), foreground_color, info_font)
            y += ( 12)
            display.drawText(x, y, "hunger:   "+ str(int(self.mi_mascota.hunger)), foreground_color, info_font)
            y += ( 12)
            display.drawText(x, y, "happiness:"+ str(int(self.mi_mascota.happiness)), foreground_color, info_font)
            y += ( 12)
            display.drawText(x, y, "health:   "+ str(int(self.mi_mascota.health)), foreground_color, info_font)
            y += ( 12)
            display.drawText(x, y, "status:   "+ self.mi_mascota.status, foreground_color, info_font)
            y += ( 12)
            display.drawText(x, y, "evolucion:"+ str(int(self.mi_mascota.evolucion)), foreground_color, info_font)

        
    


        
        
        #----------------pintamos tamagotchi
        #pintamso tamagotchi
        if (self.mi_mascota.evolucion > 0) and (self.mi_mascota.status != 'dead'):
            self.mi_mascota.x = random.randint(10,90)
            self.mi_mascota.y = random.randint(103,124)
        
        display.drawPng(self.mi_mascota.x, self.mi_mascota.y, "%s/%s" % (APP_PATH, self.getImg(self.mi_mascota)))
        #pinto el nombre
        textW=display.getTextWidth(self.mi_mascota.name,info_font)
        display.drawText(int(self.mi_mascota.x+64/2-textW/2) , int(self.mi_mascota.y)+56, self.mi_mascota.name, foreground_color, info_font)
        #pinto frasecilla
        display.drawText(5, 72, self.mi_mascota.frase, foreground_color, info_font)
        
        #luego sus ancestros muertos
        for t in self.mascotas:
            display.drawPng(t.x, t.y, "%s/%s" % (APP_PATH, self.getImg(t)))


        #----------------pintamos menu

        display.drawRect(0,190,320,240,True, 0xc1c2a7)
        display.drawPng(0, 190, "%s/%s" % (APP_PATH, "burger.png"))        
        display.drawPng(80, 190, "%s/%s" % (APP_PATH, "clean.png"))        
        display.drawPng(160, 190, "%s/%s" % (APP_PATH, "heal.png"))        
        display.drawPng(240, 190, "%s/%s" % (APP_PATH, "options.png"))
        
        
        #----------------screen update
        display.flush()
        
        
    def getImg(self, t):
        #desomponemos el gif en imageens con : https://ezgif.com/split/ezgif-2-bb9e986b4c.gif
        num = '30'
        if t.status == 'dead':
            num = random.choice(['28','29','30'])
        #huevo        
        elif t.evolucion == 0:
            num = random.choice(['00','01'])
        elif t.evolucion == 1: #bebe
            if   t.status == 'happy':  num = random.choice(['05','06','07','08','09'])
            elif t.status == 'sad':    num = '03'
            elif t.status == 'ungry':  num = '03'
            elif t.status == 'hungry': num = '02'
            elif t.status == 'sleep':  num = '04'
            elif t.status == 'broken': num = '03'
        elif t.evolucion == 2: #niño
            if   t.status == 'happy':  num =random.choice(['13','14','15'])
            elif t.status == 'sad':    num = '11'
            elif t.status == 'ungry':  num = '11'
            elif t.status == 'hungry': num = '10'
            elif t.status == 'sleep':  num = '12'
            elif t.status == 'broken': num = '11' 
        elif t.evolucion == 3: #adulto
            if   t.status == 'happy':  num = random.choice(['19','20','21'])
            elif t.status == 'sad':    num = '17'
            elif t.status == 'ungry':  num = '17'
            elif t.status == 'hungry': num = '16'
            elif t.status == 'sleep':  num = '18'
            elif t.status == 'broken': num = '17'
        elif t.evolucion == 4: #viejo
            if   t.status == 'happy':  num = random.choice(['25','26','27'])
            elif t.status == 'sad':    num = '23'
            elif t.status == 'ungry':  num = '23'
            elif t.status == 'hungry': num = '22'
            elif t.status == 'sleep':  num = '24'
            elif t.status == 'broken': num = '23'

        #print ("img/frame_" + num + "_delay-1s.png")
        return "frame_" + num + "_delay-1s.png" 
        
    def init_access_point(self, ssid):
        print('setting upu Wifi AP...')
        ap = network.WLAN(network.AP_IF)
        ap.active(True)
        ap.config(essid=ssid, authmode=network.AUTH_OPEN, channel=1, hidden=False)
        
        while not ap.active():
            pass
        print('Network config:', ap.ifconfig())



    async def handle_http_connection(self, reader, writer, tamagotchi):
        gc.collect()

        # Get HTTP request line
        data = await reader.readline()
        try:
            request_line = data.decode()
            addr = writer.get_extra_info('peername')
            print('Received {} from {}'.format(request_line.strip(), addr))
        except UnicodeError as e:
            print(f"Error decodificando datos: {e}")
            
        

        # Read headers, to make client happy (else curl prints an error)
        while True:
            gc.collect()
            line = await reader.readline()
            if line == b'\r\n': break

        # Handle the request
        if len(request_line) > 0:
            # Manejar solicitud HTTP
            request = str(request_line)
            
            if 'GET /feed' in request:
                tamagotchi.feed()
            elif 'GET /play' in request:
                tamagotchi.play()
            elif 'GET /heal' in request:
                tamagotchi.heal()
            elif 'GET /clean' in request:
                tamagotchi.clean()
            
            #si pido pagina prinicpal la sirvo, y si no, redirijo.
            #esto hace que ante peticiones de tipo detect captive auth, la cosa funcione
            #if request_path in [b'/generate_204', b'/hotspot-detect.html', b'/ncsi.txt']:
            if 'GET / HTTP' in request:
                response = self.web_page(tamagotchi)
            else:
                response=  'HTTP/1.1 302 Found\r\nLocation: /\r\n\r\n'
            

            await writer.awrite(response)

        # Close the socket
        await writer.aclose()
        # print("client socket closed")


    async def run_dns_server(self):
        """ function to handle incoming dns requests """
        udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        udps.setblocking(False)
        udps.bind(('0.0.0.0', 53))

        while True:
            try:
                # gc.collect()
                if IS_UASYNCIO_V3:
                    yield asyncio.core._io_queue.queue_read(udps)
                else:
                    yield asyncio.IORead(udps)
                data, addr = udps.recvfrom(4096)
                #print("Incoming DNS request...")

                DNS = DNSQuery(data)
                udps.sendto(DNS.response(SERVER_IP), addr)

                print("Replying: {:s} -> {:s}".format(DNS.domain, SERVER_IP))

            except Exception as e:
                print("DNS server error:", e)
                await asyncio.sleep_ms(3000)

        udps.close()


    def web_page(self, tamagotchi):
        html = f"""
        <html>
        <head>
            <title>Hola soy {tamagotchi.name}</title>
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <meta charset="utf8">
        </head>
        <body>
            <h1>Tamagotchi</h1>
            <p>Name: {tamagotchi.name}</p>
            <p>Hunger: {tamagotchi.hunger}</p>
            <p>Happiness: {tamagotchi.happiness}</p>
            <p>Health: {tamagotchi.health}</p>
            <p>Age: {tamagotchi.age}</p>
            <p>State: {tamagotchi.carita}</p>
            <button onclick="location.href='/feed'">Feed</button>
            <button onclick="location.href='/play'">Play</button>
            <button onclick="location.href='/heal'">Heal</button>
            <button onclick="location.href='/clean'">Clean</button>
        </body>
        </html>
        """
        return html


#------------------------------------------------------------------------

class DNSQuery:
    def __init__(self, data):
        self.data = data
        self.domain = ''
        tipo = (data[2] >> 3) & 15  # Opcode bits
        if tipo == 0:  # Standard query
            ini = 12
            lon = data[ini]
            while lon != 0:
                self.domain += data[ini + 1:ini + lon + 1].decode('utf-8') + '.'
                ini += lon + 1
                lon = data[ini]
        #print("DNSQuery domain:" + self.domain)

    def response(self, ip):
        #print("DNSQuery response: {} ==> {}".format(self.domain, ip))
        if self.domain:
            packet = self.data[:2] + b'\x81\x80'
            packet += self.data[4:6] + self.data[4:6] + b'\x00\x00\x00\x00'  # Questions and Answers Counts
            packet += self.data[12:]  # Original Domain Name Question
            packet += b'\xC0\x0C'  # Pointer to domain name
            packet += b'\x00\x01\x00\x01\x00\x00\x00\x3C\x00\x04'  # Response type, ttl and resource data length -> 4 bytes
            packet += bytes(map(int, ip.split('.')))  # 4bytes of IP
        # print(packet)
        return packet



#------------------------------------------------------------------------
def _handle_exception(loop, context):
    """ uasyncio v3 only: global exception handler """
    print('Global exception handler')
    sys.print_exception(context["exception"])
    sys.exit()



# def newConnect(ssid):
#     ap = network.WLAN(network.AP_IF)
#     ap.active(True)
#     ap.config(essid=ssid)
#     ap.config(authmode=0, channel=1)


#------------------------------------------------------------------------
   





































#------------------------------------------------------------------------
B1 = "burger"
B2 = "clean"
B3 = "heal"



def on_up_btn(pressed):
  if pressed:
    print ("Press: UP")

def on_down_btn(pressed):
  if pressed:
    print ("Press: DOWN")

def on_left_btn(pressed):
  if pressed:
    print ("Press: LEFT")

def on_right_btn(pressed):
  if pressed:
    print ("Press: RIGHT")

def on_a_btn(pressed):
  if pressed:
    print ("Press: A")

def on_b_btn(pressed):
  if pressed:
    print ("Press: B")

def on_home_btn(pressed):
    if pressed:
        print ("Press: HOME")
        if B1 == "burger": #si estamos en Feed/Play/Heal
            myapp.mi_mascota.feed(0)
        if B1 == "true": #si estamos en Feed/Play/Heal
            myapp.mi_mascota.play("true/lie",1)
        if B1 == "drink": #si estamos en Feed/Play/Heal
            myapp.mi_mascota.feed(1)
        
        myapp.actualizaPantalla()

def on_menu_btn(pressed):
  if pressed:
    print ("Press: MENU")
    myapp.mi_mascota.play("true/lie",1)
    myapp.actualizaPantalla()
      
def on_select_btn(pressed):
  if pressed:
    print ("Press: SELECT")
    myapp.mi_mascota.heal()
    
def on_start_btn(pressed):
    if pressed:
        print ("Press: START")
        if B1 == "burger": #si estamos en Feed/Play/Heal
            B1 = "drink"
            B2 = "play"
            B3 = "sleep"
        if B1 == "drink": #estamso en burguer/aaa/bbb
            B1 = "burger"
            B2 = "clean"
            B3 = "heal"
    

buttons.attach(buttons.BTN_UP, on_up_btn)
buttons.attach(buttons.BTN_DOWN, on_down_btn)
buttons.attach(buttons.BTN_LEFT, on_left_btn)
buttons.attach(buttons.BTN_RIGHT, on_right_btn)
buttons.attach(buttons.BTN_A, on_a_btn)
buttons.attach(buttons.BTN_B, on_b_btn)

buttons.attach(buttons.BTN_HOME, on_home_btn)
buttons.attach(buttons.BTN_MENU, on_menu_btn)
buttons.attach(buttons.BTN_SELECT, on_select_btn)
buttons.attach(buttons.BTN_START, on_start_btn)

#------------------------------------------------------------------------

    

try:
    # Instantiate app and run
    myapp = MyApp()

    if IS_UASYNCIO_V3:
        asyncio.run(myapp.start())
    else:
        loop = asyncio.get_event_loop()
        loop.run_until_complete(myapp.start())

except KeyboardInterrupt:
    print('Bye')

finally:
    if IS_UASYNCIO_V3:
        asyncio.new_event_loop()  # Clear retained state

# def main():
#     """
#     The big show!
#     """
#     global myapp
#     try:
#         # Instantiate app and run
#         myapp = MyApp()
# 
#         if IS_UASYNCIO_V3:
#             asyncio.run(myapp.start())
#         else:
#             loop = asyncio.get_event_loop()
#             loop.run_until_complete(myapp.start())
# 
#     except KeyboardInterrupt:
#         print('Bye')
# 
#     finally:
#         if IS_UASYNCIO_V3:
#             asyncio.new_event_loop()  # Clear retained state
        

# main()









