import pandas as pd
import pickle
from scipy.optimize import curve_fit
import numpy as np
import matplotlib.pyplot as plt


calibration_file_WT_R = './calibration/Cal_Watermark_Resistance.csv'
calibration_file_R_SWP = './calibration/Cal_Watermark_Datasheet.csv'
calibration_WT_R = pd.read_csv(calibration_file_WT_R)
calibration_R_SWP = pd.read_csv(calibration_file_R_SWP)
calibration_R_SWP.rename(columns={'Unnamed: 0':'SWP', 'Unnamed: 1':'WT Resistance'}, inplace=True)
calibration_R_SWP['SWP'] = - calibration_R_SWP['SWP']

def hyperbole_func(x, a):
    with np.errstate(divide='ignore', invalid='ignore'):  # Ignore division by zero and invalid value warnings
        result = a / x
        result = np.where(np.isinf(result), np.nan, result)  # Replace infinite values with NaN
    return result

# Define the linear calibration function for the second conversion
def linear_calibration_func(resistance, m, c):
    return m * resistance + c

# Resistance->SWP
popt_calibration, pcov_calibration = curve_fit(linear_calibration_func, calibration_R_SWP['WT Resistance'], calibration_R_SWP['SWP'])
# Watermark Frequency -> Resistance
popt_hyperbole, pcov_hyperbole = curve_fit(hyperbole_func, calibration_WT_R['Watermark'], calibration_WT_R['Resistance'])

# Define a function to apply both calibration functions to modify values
def double_calibration(value):
    # Apply the hyperbole function first
    hyperbole_result = hyperbole_func(value, *popt_hyperbole)
    
    # Apply the linear calibration function for the second conversion
    calibrate_result = linear_calibration_func(hyperbole_result, *popt_calibration)
    return calibrate_result

def plot_ids(
        data : pd.DataFrame, 
        ids : list = [3,4,5,6,8,9,10,13,14], 
        dates : dict = {
            "start_date":   '2024-03-08 09:00:00',
            "end_date":     '2024-04-18 09:00:00'
        }
        ):
    # Apply the double calibration function to the specified column
    data = data.loc[(data.Date >= dates["start_date"]) & (data.Date <= dates["end_date"])]
    data.sort_values("Date", inplace=True)
    data.set_index("Date", inplace=True)
    fig, ax = plt.subplots()
    for i in sorted(ids):
        ax.plot(data.loc[data.id==i,'SWP'],label=f'Plant {i}')
    plt.legend()
    plt.grid(True)
    plt.show()

#Example line
# data = pd.read_csv(filepath_or_buffer="./DataSerraGrugliasco-Labeled.csv", parse_dates=['Date'])
# data['SWP'] = data['Watermark'].apply(double_calibration)
# plot_ids(data)
