
from FiCurve import FICurve, get_fi_curve_class
from CellData import CellData
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import os
import numpy as np
import functions as fu


class Adaption:

    def __init__(self, fi_curve: FICurve):

        self.fi_curve = fi_curve

        # [[a, tau_eff, c], [], [a, tau_eff, c], ...]
        self.exponential_fit_vars = []
        self.tau_real = []

        self.fit_exponential()
        self.calculate_tau_from_tau_eff()

    def fit_exponential(self, length_of_fit=0.1):
        time_axes, mean_frequencies = self.fi_curve.get_mean_time_and_freq_traces()
        f_baselines = self.fi_curve.get_f_baseline_frequencies()
        f_infinities = self.fi_curve.get_f_inf_frequencies()
        f_zeros = self.fi_curve.get_f_zero_frequencies()
        for i in range(len(mean_frequencies)):

            if abs(f_zeros[i] - f_infinities[i]) < 20:
                self.exponential_fit_vars.append([])
                continue

            start_idx = self.__find_start_idx_for_exponential_fit(time_axes[i], mean_frequencies[i],
                                                                  f_baselines[i], f_infinities[i], f_zeros[i])

            if start_idx == -1:
                # print("start index negative")
                self.exponential_fit_vars.append([])
                continue

            # shorten length of fit to stay in stimulus region if given length is too long
            sampling_interval = self.fi_curve.get_sampling_interval()
            used_length_of_fit = length_of_fit
            if (start_idx * sampling_interval) - self.fi_curve.get_delay() + length_of_fit > self.fi_curve.get_stimulus_end():
                print(start_idx * sampling_interval, "start - end",  start_idx * sampling_interval + length_of_fit)
                print("Shortened length of fit to keep it in the stimulus region!")
                used_length_of_fit = self.fi_curve.get_stimulus_end() - (start_idx * sampling_interval)



            end_idx = start_idx + int(used_length_of_fit/sampling_interval)
            y_values = mean_frequencies[i][start_idx:end_idx+1]
            x_values = time_axes[i][start_idx:end_idx+1]
            plt.title("f_zero {:.2f}, f_inf {:.2f}".format(f_zeros[i], f_infinities[i]))
            plt.plot(time_axes[i], mean_frequencies[i])
            plt.plot(x_values, y_values)
            plt.show()
            plt.close()

            tau = self.__approximate_tau_for_exponential_fit(x_values, y_values, i)

            # start the actual fit:
            try:
                p0 = (self.fi_curve.f_zero_frequencies[i], tau, self.fi_curve.f_inf_frequencies[i])
                popt, pcov = curve_fit(fu.exponential_function, x_values, y_values,
                                       p0=p0, maxfev=10000, bounds=([-np.inf, 0, -np.inf], [np.inf, np.inf, np.inf]))

                # plt.plot(time_axes[i], mean_frequencies[i])
                # plt.plot(x_values, [fu.exponential_function(x, popt[0], popt[1], popt[2]) for x in x_values])
                # plt.show()
                # plt.close()

            except RuntimeError:
                print("RuntimeError happened in fit_exponential.")
                self.exponential_fit_vars.append([])
                continue

            # Obviously a bad fit - time constant, expected in range 3-10ms, has value over 1 second or is negative
            if abs(popt[1] > 1) or popt[1] < 0:
                print("detected an obviously bad fit")
                self.exponential_fit_vars.append([])
            else:
                self.exponential_fit_vars.append(popt)

    def __approximate_tau_for_exponential_fit(self, x_values, y_values, mean_freq_idx):
        if self.fi_curve.f_inf_frequencies[mean_freq_idx] < self.fi_curve.f_baseline_frequencies[mean_freq_idx] * 0.95:
            test_val = [y > 0.65 * self.fi_curve.f_inf_frequencies[mean_freq_idx] for y in y_values]
        else:
            test_val = [y < 0.65 * self.fi_curve.f_zero_frequencies[mean_freq_idx] for y in y_values]

        try:
            idx = test_val.index(True)
            if idx == 0:
                idx = 1
            tau = x_values[idx] - x_values[0]
        except ValueError:
            tau = x_values[-1] - x_values[0]

        return tau

    def __find_start_idx_for_exponential_fit(self, time, frequency, f_base, f_inf, f_zero):

        # plt.plot(time, frequency)
        # plt.plot((time[0], time[-1]), (f_base, f_base), "-.")
        # plt.plot((time[0], time[-1]), (f_inf, f_inf), "-")
        # plt.plot((time[0], time[-1]), (f_zero, f_zero))

        stimulus_start_idx = int((self.fi_curve.get_stimulus_start() - time[0]) / self.fi_curve.get_sampling_interval())

        # plt.plot((time[stimulus_start_idx], ), (0, ), 'o')
        #
        # plt.show()
        # plt.close()

        if f_inf > f_base * 1.1:
            # start setting starting variables for the fit
            # search for the start_index by searching for the max
            j = 0
            while True:
                try:
                    if frequency[stimulus_start_idx + j] == f_zero:
                        start_idx = stimulus_start_idx + j
                        break
                except IndexError as e:
                    return -1

                j += 1

        elif f_inf < f_base * 0.9:
            # start setting starting variables for the fit
            # search for start by finding the end of the minimum
            found_min = False
            j = int(0.05 / self.fi_curve.get_sampling_interval())
            nothing_to_fit = False
            while True:
                if not found_min:
                    if frequency[stimulus_start_idx + j] == f_zero:
                        found_min = True
                else:
                    if frequency[stimulus_start_idx + j + 1] > f_zero:
                        start_idx = stimulus_start_idx + j
                        break
                if j > 0.1 / self.fi_curve.get_sampling_interval():
                    # no rise in freq until to close to the end of the stimulus (to little place to fit)
                    return -1
                j += 1

            if nothing_to_fit:
                return -1
        else:
            # there is nothing to fit to:
            return -1

        # plt.plot(time, frequency)
        # plt.plot(time[start_idx], frequency[start_idx], 'o')
        # plt.show()
        # plt.close()

        return start_idx

    def calculate_tau_from_tau_eff(self):
        tau_effs = []
        indices = []
        for i in range(len(self.exponential_fit_vars)):
            if len(self.exponential_fit_vars[i]) == 0:
                continue
            indices.append(i)
            tau_effs.append(self.exponential_fit_vars[i][1])

        f_infinity_slope = self.fi_curve.get_f_inf_slope()
        approx_tau_reals = []
        for i, idx in enumerate(indices):
            factor = self.fi_curve.get_f_zero_fit_slope_at_stimulus_value(self.fi_curve.stimulus_values[idx]) / f_infinity_slope
            approx_tau_reals.append(tau_effs[i] * factor)

        self.tau_real = np.median(approx_tau_reals)

    def get_tau_real(self):
        return np.median(self.tau_real)

    def get_tau_effs(self):
        return [ex_vars[1] for ex_vars in self.exponential_fit_vars if ex_vars != []]

    def get_delta_a(self):
        return self.fi_curve.get_f_zero_fit_slope_at_straight() / self.fi_curve.get_f_inf_slope() / 100

    def plot_exponential_fits(self, save_path: str = None, indices: list = None, delete_previous: bool = False):
        if delete_previous:
            for val in self.fi_curve.stimulus_values():

                prev_path = save_path + "mean_freq_exp_fit_contrast:" + str(round(val, 3)) + ".png"

                if os.path.exists(prev_path):
                    os.remove(prev_path)

        time_axes, mean_freqs = self.fi_curve.get_mean_time_and_freq_traces()
        for i in range(len(self.fi_curve.stimulus_values)):
            if indices is not None and i not in indices:
                continue

            if self.exponential_fit_vars[i] == []:
                print("no fit vars for index {}!".format(i))
                continue

            plt.plot(time_axes[i], mean_freqs[i])
            vars = self.exponential_fit_vars[i]
            fit_x = np.arange(0, 0.4, self.fi_curve.get_sampling_interval())
            plt.plot(fit_x, [fu.exponential_function(x, vars[0], vars[1], vars[2]) for x in fit_x])
            plt.ylim([0, max(self.fi_curve.f_zero_frequencies[i], self.fi_curve.f_baseline_frequencies[i])*1.1])
            plt.xlabel("Time [s]")
            plt.ylabel("Frequency [Hz]")

            if save_path is None:
                plt.show()
            else:
                plt.savefig(save_path + "mean_freq_exp_fit_contrast:" + str(round(self.fi_curve.stimulus_values[i], 3)) + ".png")

            plt.close()