"""
    @release_date  : $release_date
    @version       : $release_version
    @author        : Christos Matsingos, Ka Fu Man 
    
    This file is part of the TrIPP software
    (https://github.com/fornililab/TrIPP).
    Copyright (c) 2024 Christos Matsingos, Ka Fu Man and Arianna Fornili.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, version 3.

    This program is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program. If not, see <http://www.gnu.org/licenses/>.
"""

import pandas as pd 
from tripp._model_pka_values_ import model_pka_values 
import numpy as np
from scipy import stats


def calculate_difference_to_model(input_directory, output_prefix):
    """Calculate the time evolution of the difference between PROPKA predicted
    and model pKa values.

    Parameters
    ----------
    output_directory: str
        The directory where the output CSV file will be saved.
        
    output_prefix: str
        Prefix of the output CSV file.
    
    """
    df_pka = pd.read_csv(f'{input_directory}/{output_prefix}_pka.csv')

    df_dif = pd.DataFrame()
    df_dif['Time [ps]'] = df_pka['Time [ps]']
    del df_pka['Time [ps]']
    residues = np.array(df_pka.columns)
    for residue in residues:
        if 'N+' in residue:
            residue_modified = residue.replace('N+', 'NTR')
        elif 'C-' in residue:
            residue_modified = residue.replace('C-', 'CTR')
        else:
            residue_modified = residue

        amino_acid = residue_modified[:3]
        model_value = model_pka_values[amino_acid]
        residue_data = np.around(df_pka[residue].to_numpy() - model_value, decimals=3)
        df_dif[residue] = residue_data

    df_dif.to_csv(f'{input_directory}/{output_prefix}_difference_to_model.csv', index=False)


def PCProjectionScreening(output_directory,
                          output_prefix,
                          pka_file,
                          projection_file,
                          method='Pearson',
                          start=0,
                          end=-1,
                          header=None):
    """Calculates the correlation coefficient between the property in projection_file
    and the pKa time evolution for all the ionisable residues.
    
    Parameters
    ----------
    output_directory : str
        The path of the directory where output files will be saved.
    output_prefix : str
        Output file prefix
    pka_file: str
        The path of the CSV file with the pKa values generated by the 
        Trajectory class.
    projection_file: str
        The path of the CSV file with the PC projection (or other property) values. 
        The file needs to contain the simulation time (first column) 
        and the projection value (second column) for the same frames 
        (in the same order) as in the trajectory used for the calculation 
        of the pKa values. See tutorial/files/1AKI_md1_pc1.csv for an example.
    method: str, default='Pearson'
        'Pearson' or 'Spearman' correlation.
    start: int, default=0
        Start time (ps). The correlation will be calculated using only the 
        frames with simulation time between start and end. 
        Default is 0 (beginning of the trajectory)
    end: int, default=-1
        End time (ps). The correlation will be calculated using only the frames 
        with simulation time between start and end. Default is -1 (end of the trajectory)
    header: default=None
        Default is None (no header in projection_file). 
        Use header=0 if projection_file has a header.
    """
    pKaDF = pd.read_csv(pka_file)
    ProjDF = pd.read_csv(projection_file,
                         sep=',',
                         skipinitialspace=True,
                         header=header)
    # Made sure the column name is Time [ps] and Projection.
    ProjDF.rename(columns=dict(zip(ProjDF.columns.to_list(),['Time [ps]','Projection'])), inplace=True)
    if end == -1:
        end = pKaDF['Time [ps]'].iloc[end]
    else:
        end = end
    # Slice through pKaDF and ProjDF according to the start and end provided.
    pKaDF = pKaDF[(pKaDF['Time [ps]'] >= start) & (pKaDF['Time [ps]'] <= end)]
    ProjDF = ProjDF[(ProjDF['Time [ps]'] >= start) & (ProjDF['Time [ps]'] <= end)]
    
    Correlations = []
    PValues = []
    for Residue in pKaDF.keys()[1:]:
        if method == 'Pearson':
            Correlation, PValue = stats.pearsonr(ProjDF['Projection'], pKaDF[Residue])
        elif method == 'Spearman':
            Correlation, PValue = stats.spearmanr(ProjDF['Projection'], pKaDF[Residue])
        Correlations.append(Correlation)
        PValues.append(PValue)
    OutputDF = pd.DataFrame([pKaDF.keys()[1:], Correlations, PValues]).T
    OutputDF.columns = ['Residue', 'Correlation', 'p-value']
    OutputDF.to_csv(f'{output_directory}/{output_prefix}.csv', index=False)
