# # -*- coding: utf-8 -*-
# """
# Created on Sat Mar  4 12:59:45 2023

# @author: simon
# """

# import serial
# import pandas as pd
# import sys
# import time

# import tkinter as tk
# from multiprocessing import Process, Pipe

# #window = tk.Tk()

# def readValues(conn):
#     for i in range(10):
#         print(i)
#         if conn.poll():
#             print(conn.recv())
#         time.sleep(1.5)
#     # Read = False
#     # while True:
#     #     if conn.poll():
#     #         print(conn.recv())
#     #         # if conn.recv() == 'start':
#     #         #     # if not Read:
#     #         #     #     serialPort = serial.Serial(port='COM7', baudrate=115200, timeout=3)
#     #         #     # print('received start')
#     #         #     # Read = True
#     #         # else: 
#     #         #     Read = False
#     #         #     serialPort.close()
#     #         if Read:
#     #             if serialPort.inWaiting():
#     #                 print(serialPort.readline().decode('Ascii'))
#     #             else:
#     #                 time.sleep(0.1)
#     #     else:
#     #         print('waiting')
#     #         time.sleep(1)
# def onClosing():
#     global serialPort
#     if tk.messagebox.askokcancel("Quit","Wanna quit?"):
#         serialPort.close()
#         p.kill()
#        # window.destroy()  

# def buttonPressed(button, conn):
#     if button == 'start':
#         print(button)
#         conn.send('start')
#     else:
#         #Read = False
#         conn.send('stop')
    
# if __name__ == '__main__':    
#     print('hi')
    
#     parent_conn, child_conn = Pipe(duplex=True)
#     p = Process(target=readValues, args=(child_conn,))
#     p.start()
#     parent_conn.send('start')
#     time.sleep(10)
#     parent_conn.send('stop')
#     p.kill()

# window.title("Visualize")
# top = tk.Frame(window)
# top.pack(side=tk.TOP)
# buttonStart = tk.Button(window,text='Start', 
#                         bg='black',fg='white',
#                         command=lambda x='start':buttonPressed(x,parent_conn));
# buttonStart.pack(padx=10,pady=10, in_=top,side=tk.LEFT)
# buttonStop = tk.Button(window,text='Stop', 
#                         bg='black',fg='white',
#                         command=lambda x='stop':buttonPressed(x,parent_conn));
# buttonStop.pack(padx=10,pady=10, in_=top,side=tk.LEFT)
# #f1 = tk.Frame(window, height=1000,width=2000)
# #f1.pack()
# window.protocol("WM_DELETE_WINDOW",onClosing)
# window.mainloop()


# #serialPort = serial.Serial(port='COM7',baudrate=115200,timeout=3);
# df = pd.DataFrame();


# #while True:
# #    if True #serialPort.inWaiting > 0:
#         #serialString = serialPort.readline().decode('Ascii');
# #        if(serialString.startswith('X')):
# #            print(serialString);

   
    
    
from multiprocessing import Process, Pipe, Queue
import time
import serial
import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import pandas as pd
import numpy as np

def f(conn,q):
    ongoing = True
    reading = False
    serialPort = serial.Serial(port='COM7',baudrate=115200,timeout=1)
    while ongoing:
        if conn.poll():
            rec = conn.recv()
            if rec == 'start':
                reading = True
                #if not serialPort.isOpen():
                #    print('open serial port')
                #serialPort.close()
                #    serialPort = serial.Serial(port='COM7',baudrate=115200,timeout=1)
                #else:
                #    print('already open')
            if rec == 'stop':
                reading = False
               # serialPort.close()
            if rec == 'kill':
                serialPort.close()
                #print(data)
                ongoing=False
        if serialPort.inWaiting() > 0:
            if reading:
                msg = serialPort.readline()
                try:
                    msg = msg.decode("Ascii")
                except:
                    print("failed")
                if msg.startswith("X"):
                    q.put(msg)
            else:
                serialPort.read_all()
    #time.sleep(0.001)
    conn.close()
    
def buttonPressed(button, conn,q):
    conn.send(button)
    if button == 'stop':
        data =[]
        while not q.empty():
            dString = q.get()
            dString = dString.rstrip("\r\n")
            tmp = dString.split('\t')
            d = {}
            print(tmp)
            for elem in tmp:
                tmp1 = elem.split(':')
                d[tmp1[0]] = int(tmp1[1])
            data.append(d)
        df = pd.DataFrame(data)
        df['sqr'] = df.apply(lambda x: 
                           np.sqrt(x['X']**2+x['Y']**2+x['Z']**2),axis=1)
        for l in window.pack_slaves():
            if isinstance(l, tk.Canvas):
                l.destroy()
        figure = plt.Figure(figsize=(10,6),dpi=100)
        ax2 = figure.add_subplot(111)
        line = FigureCanvasTkAgg(figure,window)
        line.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH)
        #ax2.hline(173,df.shape[0])
        #df.plot(kind='line',legend=True,ax=ax2, grid=True)
        #df.plot.line(y=173)
        ax2.plot(df['X'],'-b',label='X',)
        ax2.plot(df['Y'],'-y',label='Y')
        ax2.plot(df['Z'],'-g',label='Z')
        ax2.plot(df['sqr'],color='black',label='sqr')
        axl = ax2.twinx()
        axl.plot(df['F'],'-*',label='Freefallcounter')
        axl.legend()
        ax2.grid()
        ax2.axhline(y=173,color='red')
        ax2.legend()

def onClosing():
    if tk.messagebox.askokcancel("Quit","Wanna quit?"):
        window.destroy() 

if __name__ == '__main__':
    parent_conn, child_conn = Pipe(duplex=True)
    q = Queue()
    p = Process(target=f, args=(child_conn,q,))
    p.start()
    window = tk.Tk()
    window.title("Visualize")
    top = tk.Frame(window)
    top.pack(side=tk.TOP)
    buttonStart = tk.Button(window,text='Start', 
                            bg='black',fg='white',
                            command=lambda x='start':buttonPressed(x,parent_conn,q));
    buttonStart.pack(padx=10,pady=10, in_=top,side=tk.LEFT)
    buttonStop = tk.Button(window,text='Stop', 
                            bg='black',fg='white',
                            command=lambda x='stop':buttonPressed(x,parent_conn,q));
    buttonStop.pack(padx=10,pady=10, in_=top,side=tk.LEFT)

    window.protocol("WM_DELETE_WINDOW",onClosing)
    window.mainloop()
    
    parent_conn.send('kill')
    p.join()

