import pandas as pd
from loguru import logger


class GetData:
    @staticmethod
    def associate_inv_mppt_id(df):
        try:
            current_column_list = [col_name for col_name in df if 'current' in col_name]
            voltage_column_list = [col_name for col_name in df if 'voltage' in col_name]
            current_column_list.sort()
            voltage_column_list.sort()

            df_mppt = pd.DataFrame()
            for n_mppt in range(len(current_column_list)):
                df_temp = df[['datetime', 'inv_id', 'hour', 'tilt_irradiance', voltage_column_list[n_mppt],
                              current_column_list[n_mppt]]]
                df_temp['mppt_id'] = current_column_list[n_mppt]
                df_temp['mppt_id'] = df_temp['mppt_id'].str.replace('current_', '')
                df_temp.rename(columns={voltage_column_list[n_mppt]: 'voltage_mppt',
                                        current_column_list[n_mppt]: 'current_mppt'}, inplace=True)
                if df_mppt.empty:
                    df_mppt = df_temp
                else:
                    df_mppt = pd.concat([df_mppt, df_temp], axis=0)
                    df_mppt.reset_index(drop=True, inplace=True)
            df_mppt.sort_values(['inv_id', 'mppt_id'], inplace=True)
            df_mppt['inv_id_mppt_id'] = df_mppt['inv_id'] + '_' + df_mppt['mppt_id']
            df_mppt.dropna(axis=0, inplace=True)
            df_mppt.reset_index(drop=True, inplace=True)
            return df_mppt
        except Exception as e:
            logger.exception(f'Exception - {e}')

    @staticmethod
    def multiply_mppt_coefficients(df_mppt, df_coefficients):
        try:
            df = pd.merge(df_mppt, df_coefficients, on='inv_id_mppt_id', how='left')
            logger.debug(f'null rows after mppt coefficient multiplication - {df.isnull().sum()}')
            df["coefficient"].fillna(1, inplace=True)
            df.reset_index(drop=True, inplace=True)
            df['current_mppt'] = df['current_mppt'] * df["coefficient"]
            df.drop(['coefficient', 'inv_id_mppt_id'], axis=1, inplace=True)
            return df
        except Exception as e:
            logger.exception(f'Exception - {e}')


