import matplotlib.pyplot as plt
import numpy as np
import io, os
import re

# use ggplot style for more sophisticated visuals
plt.style.use('ggplot')

def live_plotter(x_vec,y1_data,y2_data,y3_data,line1,line2,line3,identifier='',pause_time=0.1):
    if line1==[]:
        # this is the call to matplotlib that allows dynamic plotting
        plt.ion()
        fig = plt.figure(figsize=(13,6))
        ax = fig.add_subplot(111)
        # create a variable for the line so we can later update it
        line1, = ax.plot(x_vec,y1_data,'-o',alpha=0.8)
        line2, = ax.plot(x_vec,y2_data,'-o',alpha=0.8)
        line3, = ax.plot(x_vec,y3_data,'-o',alpha=0.8)
        #update plot label/title
        plt.ylabel('Y Label')
        plt.title('Title: {}'.format(identifier))
        plt.show()

    # after the figure, axis, and line are created, we only need to update the y-data
    line1.set_ydata(y1_data)
    line2.set_ydata(y2_data)
    line3.set_ydata(y3_data)
    # adjust limits if new data goes beyond bounds
    if np.min(y1_data)<=line1.axes.get_ylim()[0] or np.max(y1_data)>=line1.axes.get_ylim()[1]:
        plt.ylim([np.min(y1_data)-np.std(y1_data),np.max(y1_data)+np.std(y1_data)])
    # this pauses the data so the figure/axis can catch up - the amount of pause can be altered above
    plt.pause(pause_time)

    # return line so we can update it again in the next iteration
    return [line1, line2, line3]



n_samples = 60
x_vec = np.linspace(0,1,n_samples+1)[0:-1]
t_vec = n_samples*[0]
v_vec = n_samples*[0]
i_vec = n_samples*[0]
line1 = []
line2 = []
line3 = []

tty = io.TextIOWrapper(io.FileIO(os.open("/dev/ttyACM1", os.O_NOCTTY | os.O_RDWR), "r+"))

for line in iter(tty.readline, None):
    ttyl = line.strip()

    if re.match('.*temp.*', ttyl):
        t_vec += [float(re.match('.*val = (.*?) .*', ttyl).group(1))]

    if (len(t_vec) > n_samples and re.match('.*v1.*', ttyl)):
        v_vec += [float(re.match('.*val = (.*)', ttyl).group(1))]

    if (len(v_vec) > n_samples and re.match('.*i1.*', ttyl)):
        i_vec += [float(re.match('.*val = (.*)', ttyl).group(1))]

    if len(i_vec) > n_samples:
        t_vec = t_vec[1:]
        v_vec = v_vec[1:]
        i_vec = i_vec[1:]
        print('last triplet: {}, {}, {}'.format(t_vec[-1], v_vec[-1], i_vec[-1]))
        [line1, line2, line3] = live_plotter(x_vec, t_vec, v_vec, i_vec, line1, line2, line3)

    if len(t_vec) > n_samples+1:
        t_vec = t_vec[-n_samples-1:]
    if len(v_vec) > n_samples+1:
        v_vec = v_vec[-n_samples-1:]
    if len(i_vec) > n_samples+1:
        i_vec = i_vec[-n_samples-1:]
