# main.py (Código que se convertirá en APK)
import kivy
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.clock import Clock
from kivy.utils import get_color_from_hex
import requests
import json
import time

# --- CONFIGURACIÓN CLAVE ---
# REEMPLAZA ESTO CON LA IP REAL DE TU RASPBERRY PI
RASPBERRY_PI_IP = '192.168.71.159 '
API_LECTURA = f'http://{RASPBERRY_PI_IP}:5000/api/lectura'
API_CONTROL = f'http://{RASPBERRY_PI_IP}:5000/api/compuerta'
# ---------------------------

class GasMonitor(BoxLayout):
    def __init__(self, **kwargs):
        super(GasMonitor, self).__init__(orientation='vertical', padding=10, spacing=10)
        
        # Estado de conexión
        self.status_label = Label(text="Iniciando Conexión...", size_hint_y=None, height=50)
        self.add_widget(self.status_label)

        # Contenedor para mediciones
        self.mediciones_layout = BoxLayout(orientation='vertical', spacing=5)
        self.labels = {}
        sensores = ['CO', 'CH4', 'AIRE']
        
        for sensor in sensores:
            self.labels[sensor] = Label(text=f'{sensor}: --- PPM', font_size='24sp')
            self.mediciones_layout.add_widget(self.labels[sensor])
            
        self.add_widget(self.mediciones_layout)
        
        # Botones de control
        self.add_widget(Label(text="Control de Compuerta (Buzzer)", size_hint_y=None, height=30))
        
        self.control_layout = BoxLayout(spacing=10, size_hint_y=None, height=80)
        
        btn_abrir = Button(text="ABRIR (ON)", background_color=get_color_from_hex('#006600'))
        btn_abrir.bind(on_press=lambda instance: self.enviar_control('abrir'))
        self.control_layout.add_widget(btn_abrir)
        
        btn_cerrar = Button(text="CERRAR (OFF)", background_color=get_color_from_hex('#CC0000'))
        btn_cerrar.bind(on_press=lambda instance: self.enviar_control('cerrar'))
        self.control_layout.add_widget(btn_cerrar)
        
        self.add_widget(self.control_layout)
        
        # Iniciar el ciclo de actualización cada 2 segundos
        Clock.schedule_interval(self.obtener_datos, 2)

    def obtener_datos(self, dt):
        """Realiza la solicitud GET a la API de la Raspberry Pi."""
        try:
            response = requests.get(API_LECTURA, timeout=3)
            data = response.json()

            if data.get("status") == "OK":
                self.status_label.text = f"CONECTADO: {data['timestamp']}"
                self.status_label.color = get_color_from_hex('#00CC00')
                
                self.labels['CO'].text = f"CO: {data['CO']:.2f} PPM"
                self.labels['CH4'].text = f"CH4: {data['CH4']:.2f} PPM"
                self.labels['AIRE'].text = f"AIRE: {data['AIRE']:.2f} PPM"
            else:
                self.status_label.text = f"ERROR API: {data.get('message', 'Desconocido')}"
                self.status_label.color = get_color_from_hex('#FF9900')
                
        except requests.exceptions.ConnectionError:
            self.status_label.text = "ERROR: No se puede conectar a la PI"
            self.status_label.color = get_color_from_hex('#CC0000')
        except requests.exceptions.Timeout:
            self.status_label.text = "ERROR: Tiempo de espera agotado"
            self.status_label.color = get_color_from_hex('#FF6600')
        except Exception as e:
            self.status_label.text = f"ERROR: {e}"
            self.status_label.color = get_color_from_hex('#CC0000')

    def enviar_control(self, accion):
        """Envía una solicitud POST para abrir o cerrar la compuerta (buzzer)."""
        url = f'{API_CONTROL}/{accion}'
        try:
            response = requests.post(url, timeout=3)
            if response.status_code == 200:
                self.status_label.text = f"Comando enviado: {accion.upper()}"
            else:
                self.status_label.text = f"Fallo de control: {response.status_code}"
        except Exception as e:
            self.status_label.text = f"Fallo al enviar comando: {e}"

class GasApp(App):
    def build(self):
        self.title = 'KEL AviGasDetector'
        return GasMonitor()

if __name__ == '__main__':
    GasApp().run()
