import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons

def tracer(event) :
     
    x = np.linspace(0, sTmax.val, 1000)
    y1 = sK.val * np.exp(-x * sT.val / 20) + 100 - sK.val
    y2 = 100 - y1
    line2.set_data(x, y2)
    t = 20 / sT.val * np.log(2)
    if aff :
        line1.set_data(x, y1)
        reticule.set_data([0, t, t, 0, t, t], [100 - sK.val / 2, 100 - sK.val / 2, sK.val / 2, sK.val / 2, sK.val / 2, 0])
    else :
        line1.set_data([], [])
        reticule.set_data([0, t, t], [sK.val / 2, sK.val / 2, 0])
    ax.set_xlim(0, sTmax.val)
    ax.set_ylim(0, 100)
    ax.texts = []
    ax.text(t, 1.5, r'$t_{1/2} = ' + str(round(t, 3 - int(np.log(t) / np.log(10)))) + '$', color = (.3, .3, .3), size = 25)
    plt.draw()

def change_aff(event) :
    
    global aff, bouton_aff
    
    aff ^= True
    ax_aff.texts = []
    if aff : bouton_aff = Button(ax_aff, 'Masquer réactif')
    else : bouton_aff = Button(ax_aff, 'Afficher réactif')
    bouton_aff.on_clicked(change_aff)
    bouton_aff.label.set_size(20)
    tracer(1)

fig = plt.figure()
ax = fig.add_subplot(111)
position = list(ax.get_position().bounds)
position[2] -= .3
ax.set_position(position)
ax.tick_params(axis = 'both', labelsize = 20, pad = 5)
ax.set_title(r'Réactif $\rightarrow$ Produit', size = 30, pad = 10)
ax.set_xlabel('temps (s)', size = 30)
ax.set_ylabel('proportion (%)', size = 30)


line1, = ax.plot([], [], label = 'Réactif', linewidth = 3)
line2, = ax.plot([], [], color = (1, .5, 0), label = 'Produit', linewidth = 3)
ax.legend(prop = {'size' : 20})
reticule, = ax.plot([], [], ':', linewidth = 2, color = (.3, .3, .3))

ax_Tmax = fig.add_axes([.7, .1, .2, .05])
sTmax = Slider(ax_Tmax, r'$t_{max} \;(\mathrm{s})$', 0, 30, valinit = 10)
sTmax.on_changed(tracer)
sTmax.label.set_size(20)
sTmax.valtext.set_size(20)

ax_T = fig.add_axes([.7, .2, .2, .05])
sT = Slider(ax_T, r'$T \;(^\circ\mathrm{C})$', 0.01, 100, valinit = 25)
sT.on_changed(tracer)
sT.label.set_size(20)
sT.valtext.set_size(20)

ax_K = fig.add_axes([.7, .3, .2, .05])
sK = Slider(ax_K, r'équilibre', 0, 100, valinit = 100)
sK.on_changed(tracer)
sK.label.set_size(20)
sK.valtext.set_size(20)

aff = True
ax_aff = fig.add_axes([.74, .5, .15, .1])
bouton_aff = Button(ax_aff, 'Masquer réactif')
bouton_aff.on_clicked(change_aff)
bouton_aff.label.set_size(20)

tracer(1)
mng = plt.get_current_fig_manager()       # Vous pouvez décommenter ça si vous utilisez 'TkAgg'
mng.window.state('zoomed')
plt.show()