"""
Menú para el procesador estadístico
"""

import logging
from .base_menu import BaseCommandProcessor
from prettytable import PrettyTable

logger = logging.getLogger(__name__)

class StatisticsCommandProcessor(BaseCommandProcessor):
    def __init__(self, stats_processor):
        super().__init__()
        self.processor = stats_processor

    def _show_menu(self):
        """Muestra el menú de comandos disponibles"""
        estados = []
        if self.processor.verbose:
            estados.append("VERBOSE")
        if self.processor.debug:
            estados.append("DEBUG")
            
        print(f"\nEstado: {' | '.join(estados) or 'NORMAL'}")
        print(f"Períodos activos: {self.processor.metrics['active_periods']}")
        print("\nComandos disponibles:")
        print("  X - Salir")
        print("  V - Toggle modo Verbose")
        print("  D - Toggle modo Debug")
        print("  S - Mostrar estado")
        print("  P - Estado de períodos")
        print("  L - Limpiar pantalla")
        print("  C - Mostrar configuraciones")

    def _process_command(self, cmd):
        """Procesa un comando individual"""
        if cmd == 'X':
            self.running = False
            self.processor.running = False
        elif cmd == 'V':
            self.processor.toggle_verbose()
        elif cmd == 'D':
            self.processor.toggle_debug()
        elif cmd == 'S':
            self._show_status()
        elif cmd == 'P':
            self._show_periods()
        elif cmd == 'L':
            self._clear_screen()
        elif cmd == 'C':
            self._show_configurations()
        else:
            print("Comando no reconocido")

    def _show_status(self):
        """Muestra el estado actual del sistema"""
        metrics = self.processor.get_metrics()
        print("\n=== Estado del Sistema ===")
        print(f"Mediciones procesadas: {metrics['processed_measurements']}")
        print(f"Registros generados: {metrics['generated_records']}")
        print(f"Períodos activos: {metrics['active_periods']}")

    def _show_periods(self):
        """Muestra el estado de los períodos actuales"""
        metrics = self.processor.get_metrics()
        print("\n=== Estado de Períodos ===")
        
        table = PrettyTable()
        table.field_names = ["DMAC", "Entrada", "Inicio Período"]
        
        for period in metrics['current_periods']:
            table.add_row([
                period['dmac'],
                period['idEntrada'],
                period['period_start']
            ])
            
        print(table)

    def _show_configurations(self):
        """Muestra la tabla de configuraciones"""
        print("\n=== Configuraciones de Sensores ===")
        table = PrettyTable()
        table.field_names = [
            "Sistema", "Entrada", "Val. Min", "Val. Max", 
            "T.Max (seg)", "Factor", "Genera Alarma"
        ]
        
        configs = self.processor.configs
        for key, config in sorted(configs.items()):
            table.add_row([
                key[0],                    # Sistema
                key[1],                    # Entrada
                config['vMin1'],           # Valor mínimo
                config['vMax1'],           # Valor máximo
                config['tMax1'],           # Tiempo máximo
                config.get('factor', 1),   # Factor
                'Sí' if config['generaAlarma'] else 'No'
            ])
            
        print(table)