import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

columns_names=["name","num_file","xDim","yDim","m2","num_mics","num_comb","freq","NMSE","SSIM","pattern","p_real","p_predicted","p_previous"]

def preprocess_df(dataframe):
  
  num_mics = np.unique(dataframe['num_mics'].values)
  list_str_freq = np.unique(dataframe['freq'].values)
  freq = [freq for freq in list_str_freq if freq != 'freq']

  dict_loss_SSIM = {}
  dict_loss_NMSE = {}

  for mics in num_mics:
    data_SSIM = pd.DataFrame()
    data_NMSE = pd.DataFrame()

    for frequency in freq:
      df = dataframe[(dataframe['freq']==frequency) & (dataframe['num_mics']== mics)]
      values_NMSE = np.array(df['NMSE'],dtype=float)
      values_SSIM = np.array(df['SSIM'],dtype=float)    

      data_SSIM[frequency] = pd.Series(values_SSIM.mean())
      data_NMSE[frequency] = pd.Series(values_NMSE.mean())

      dict_loss_SSIM[mics] = pd.DataFrame(data=np.array([values_SSIM.mean()]),columns=[frequency]).values  
      dict_loss_NMSE[mics] = pd.DataFrame(data=np.array([values_NMSE.mean()]),columns=[frequency]).values

    loss_SSIM = data_SSIM.values
    loss_NMSE = data_NMSE.values

    dict_loss_SSIM[mics] = np.reshape(loss_SSIM,(40,))
    dict_loss_NMSE[mics] = np.reshape(loss_NMSE,(40,))  

    labels = data_SSIM.columns
  
  return (dict_loss_SSIM,dict_loss_NMSE), freq, labels


def plot_evaluation(dicts, freq, labels,num_mics=None):

  dict_loss_SSIM = dicts[0]
  dict_loss_NMSE = dicts[1]

  empty_array = np.empty(len(labels))    #Placeholder
  for i, label in enumerate(labels):
    label = int(label)
    empty_array[i] = label

  labels = np.sort(empty_array.astype(int))
  labels_idx = [0,5,9,12,15,17,19,20,31,39]
  labels_used = [labels[idx] for idx in labels_idx]
  #SSIM
  plt.figure(figsize=(32,10))                                       
  plt.subplot(121)

  if type(num_mics) == list:
    keys = [mic for mic in num_mics]
    keys_leg = np.sort(np.array([int(elemento) for elemento in keys]))

  else:
    keys = [mic for mic in dict_loss_SSIM.keys() if mic != 'num_mics']
    keys_leg = np.sort(np.array([int(elemento) for elemento in keys]))
  for mic in keys:
    plt.plot(freq,dict_loss_SSIM[mic],markevery=2)

  legend = []
  keys_leg = np.sort(np.array([int(elemento) for elemento in keys]))
  for n in keys_leg:
    legend.append(f'{n} mics')
  plt.xticks(ticks=labels_idx,labels=labels_used)
  plt.xlabel('frequency [Hz]')
  plt.ylabel('MSSIM')
  plt.title('Mean Structural Similarity')
  plt.legend(legend)
  plt.grid(color='k',linewidth=1)

  #NMSE
  plt.subplot(122)

  for mic in keys:
    plt.plot(freq,db(dict_loss_NMSE[mic]),markevery=2)

  plt.xticks(ticks=labels_idx,labels=labels_used)
  plt.xlabel('frequency [Hz]')
  plt.ylabel('NMSE(dB)')
  plt.title('Normalized Mean Squared Error')
  plt.legend(legend)
  plt.grid(color='k',linewidth=1)
  plt.show()


def db(dict_loss):

  dict_in_dB = 20*np.log10(abs(dict_loss/max(dict_loss)))

  return dict_in_dB