import traceback
import sys

import pandas as pd
from loguru import logger

from base.base import BaseDataConverter


# FIXME: костыль для выключения предупреждения "replace deprecated"
pd.set_option('future.no_silent_downcasting', True)


class DataConverter(BaseDataConverter):

    @staticmethod
    def _replace_bool(dataframe: pd.DataFrame) -> pd.DataFrame:
        try:
            bool_columns = dataframe.columns[dataframe.isin([True, False]).any()]
            dataframe[bool_columns] = dataframe[bool_columns].replace({True: 1, False: 0})
            return dataframe
        except:
            # TODO: Обработка исключений!
            # TODO: Осмысленное сообщение в лог. Без traceback и прочего подобного.
            return None
    
    @staticmethod
    def _fix_headers(dataframe: pd.DataFrame) -> pd.DataFrame:
        correct_columns = [
                "time", "Closing", "Electrode Force, N FE", "Electrode Force, N ME",
                "Force Control FE", "Force Control ME", "Hold Position ME", "Oncomming",
                "Position Control FE", "Position Control ME", "Relief",
                "Rotor Position, mm FE", "Rotor Position, mm ME",
                "Rotor Speed, mm/s FE", "Rotor Speed, mm/s ME",
                "Squeeze", "Welding", "Welding Current ME", "Welding Voltage ME"
            ]
        try:
            correct_mapping = {name.lower(): name for name in correct_columns}
            new_columns = []
            for col in dataframe.columns:
                fixed_col = correct_mapping.get(col.lower(), col)
                new_columns.append(fixed_col)
            dataframe.columns = new_columns
            return dataframe
        except:
             # TODO: Обработка исключений!
            # TODO: Осмысленное сообщение в лог. Без traceback и прочего подобного.
            return None

    def convert_data(self, files: list[str]) -> None:
        try:
            dataframes = [pd.read_csv(file) if file != '' else None for file in files]
            renamed_dataframes = list(map(self._fix_headers, dataframes))
            converted_dataframes = list(map(self._replace_bool, renamed_dataframes))
        except:
            # TODO: Обработка исключений!
            # Get the traceback object
            tb = sys.exc_info()[2]
            tbinfo = traceback.format_tb(tb)[0]
            pymsg = "Traceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
            # TODO: Осмысленное сообщение в лог. Без traceback и прочего подобного.
            logger.error(pymsg)
            converted_dataframes = [None]
        finally:
            self._mediator.notify(self, converted_dataframes)
