import logging
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy import Column, Integer, String, Text, Boolean
from sqlalchemy.orm import registry, Session
from common.proto.pcep_pb2 import LspDescriptor
import uuid

# Configuración del logger
logging.basicConfig(level=logging.INFO)
LOGGER = logging.getLogger(__name__)

# Base para los modelos declarativos
Base = registry().generate_base()
class LspModel(Base):
    __tablename__ = 'lsp'

    lsp_uuid        = Column(UUID(as_uuid=True), primary_key=True)  
    srp             = Column(Text, nullable=True)  # Puede ser null
    lsp             = Column(Text, nullable=True)  # Se almacena en JSON
    path            = Column(Text, nullable=True)  # Se almacena en JSON
    associationlist = Column(Text, nullable=True)  # Se almacena en JSON

    def __repr__(self):
        return (f"<Lsp(lsp_uuid='{self.lsp_uuid}', srp='{self.srp}', lsp='{self.lsp}', "
                f"path='{self.path}', associationlist='{self.associationlist}')>")
    
    @staticmethod
    def get_all_columns():
        return LspModel.__table__.columns.keys()
    
    # @staticmethod
    # def get_all_data():
    #     """Ejecuta 'SELECT * FROM lsp' y devuelve los resultados."""
    #     session = Session()
    #     try:
    #         result = session.execute(text("SELECT * FROM lsp"))  # Ejecuta la consulta SQL pura
    #         rows = result.fetchall()  # Obtiene todas las filas
    #         session.close()
    #         return rows  # Devuelve una lista de tuplas con los datos
    #     except Exception as e:
    #         session.rollback()
    #         LOGGER.error(f"Error al obtener los datos de la base de datos: {e}")
    #         return None

    @classmethod
    def convert_LspDescriptor_to_row(cls, request):
        """
        Create an instance of Lsp from a request object.
        
        Args:   
            request: The request object containing the data.
            
        Returns: 
            An instance of Lsp initialized with data from the request.
        """
        return cls(
            lsp_uuid            = uuid.UUID(request.lsp_uuid),  # Convertir a UUID de la request
            srp                 = request.srp,
            lsp                 = request.lsp,
            path                = request.path,
            associationlist    = request.associationlist
        )
    
    @classmethod
    def convert_row_to_LspDescriptor(cls, row):
        """
        Create and return an LspDescriptor object from a Lsp instance.
        
        Args:   
            row: The Lsp instance (row) containing the data.
            
        Returns: 
            LspDescriptor object
        """
        response = LspDescriptor()
        response.lsp_uuid = str(row.lsp_uuid)  # Si lsp_uuid es UUID, convertir a string
        response.srp = row.srp
        response.lsp = row.lsp
        response.path = row.path
        response.associationlist = row.associationlist
        return response
