import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import constants as c


#Tar inn T i kelvin
def t_star_func(T):
    return c.tr * np.exp(
                            (c.A0 / c.R) *
                                (
                                    (
                                    c.Teq**2 / (T * (c.Teq - T)**2)
                                    ) -
                                    (
                                    c.Teq**2 / (c.Tr * (c.Teq - c.Tr)**2)
                                    )
                                ) +
                            (c.Qd / c.R ) *
                                (
                                    (1 / T) - (1 / c.Tr)
                                )
                        )

#find time until a fraction X is transformed
#at isothermal conditions, given that X(t_star) = X_c
#Tar inn T i kelvin
def t_func_isotherm(X, T):
    t_star = t_star_func(T)
    return t_star * np.power( np.log(1- X) / np.log(1-c.Xc) , 1 / c.n)


def plot_C_curves(T_min = c.T_min_c_curve, T_max = 470):
    X_vals = np.arange(0.05,1,step=0.05)
    T_line = np.linspace(T_min, T_max, 100) + 273

    plt.figure(figsize=[15,7])

    cmap = cm.get_cmap('plasma_r')
    label_counter = 3
    color = cmap(X_vals[0])
    for X in X_vals:
        if label_counter == 3:
            color = cmap(X+0.15)
            plt.plot(t_func_isotherm(X,T_line), T_line - 273, color=color,
                     label = 'X = '+str(round(X,2)), linestyle = ':')
            label_counter = 0
        else:
            plt.plot(t_func_isotherm(X,T_line), T_line - 273, color = color)
            label_counter += 1

    if T_max > 440 and T_min < 420:
        plt.plot([0,max(t_func_isotherm(X_vals[-1], T_line))], [c.Teq - 273,c.Teq - 273],
                 color='green', linestyle = '--', label =r'$T_{eq}$')
    plt.xscale('log')
    plt.legend()
    plt.xlabel('Time [s]')
    plt.ylabel('Temperature [\u2103]')
    plt.title(r'T-t curves for different fractions transformed, distance between lines is $\Delta X = 0.05$')
    plt.show()
