import pandas

from bclearer_core.objects.registers.registers import Registers


class PandasTableRegisters(Registers[pandas.DataFrame]):
    def __init__(
            self,
            owning_registry,
            name: str,
            content: pandas.DataFrame | None = None):
        super().__init__(
            owning_registry=owning_registry,
            name=name,
            content=content)
        
    def get_model(
            self):
        pandas_dataframe = \
            self.get_content()
        
        return \
            {
                "table_name": self.name,
                "num_columns": len(pandas_dataframe.columns),
                "num_rows": len(pandas_dataframe),
                "columns": [
                    {
                        "name": col,
                        "dtype": str(pandas_dataframe[col].dtype),
                        "nullable": bool(pandas_dataframe[col].isnull().any())
                    }
                    for col in pandas_dataframe.columns
                ]
            }
        
    def get_content(
            self) \
            -> pandas.DataFrame:
        content = \
            super().get_content()
        
        return \
            content.copy()
    
    def export_to_disk(
            self, 
            base_folder_path: str):
        pandas_dataframe = \
            self.get_content()
        
        # TODO: This should support multiple formats!
        file_path = \
            f"{base_folder_path}/{self.name}.csv"
        
        pandas_dataframe.to_csv(
            file_path,
            index=False)
        
    def __str__(self) -> str:
        return \
            f"PandasTableRegisterLatest(name={self.name}, rows={len(self._content) if self._content is not None else 'None'})"
