from AppliDef import *
from SketchIDE import *
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import serial
import keyboard
import subprocess
import time


class FrmAcquisition(tk.Toplevel):
    def __init__(self, container, RatioX, RatioY, RatioY2, Appli):
        tk.Toplevel.__init__(self, container)
        self.MainAppli = Appli
        self.parent = container
        self.RatioX = RatioX
        self.RatioY = RatioY
        self.RatioY2 = RatioY2
        self.TableurAcqui = None
        self.ParaAcqui = None
        self.ConnectSerial = None
        self.USBConnected = False
        self.Dt = 0.1
        self.DureeTotalAcqui = 10
        self.DureeTrigg = 0
        self.Trigg = 0
        self.TempsAcqui = 0
        self.TempsAcquiTrigg = 0
        self.Data_Acqui = []
        self.Data_Temps = []
        self.Data_Acqui_Trigg = []
        self.Data_Temps_Trigg = []
        self.Declenchement = 0
        self.ValSeuil = 0
        self.Source = 0
        self.AcquiEnCours = False
        self.PinActif = [True, False, False, False, False, False]
        self.SketchINOAcqui = 'Sketchs/Saves/Codes/Acqui/Acqui.ino'
        self.Televersement = False
        self.ListPinActif = []

        screen = ctypes.windll.user32
        FrmFond = Image.open('Media/FrmAcqui/Fond/Fond.bmp')
        self.SX = int((float(FrmFond.size[0]) * float(self.RatioX)))
        self.SY = int((float(FrmFond.size[1]) * float(self.RatioY)))

        self.ImgFrmFond = []
        self.ImgFrmFond = RedimImg(self.SX, self.SY, 'Media/FrmAcqui/Fond/')
        self.CanvasFrmFond = CanvasApp(self, width=self.SX, height=self.SY)
        self.ImgCanvasFrmFond = self.CanvasFrmFond.create_image(0, 0, anchor=tk.NW, image=self.ImgFrmFond[0])

        self.geometry(str(self.SX) + "x" + str(self.SY) + "+" + str(int(screen.GetSystemMetrics(0) * 0.002)) + "+" +
                      str(int(screen.GetSystemMetrics(1) * 0.031)))
        self.resizable(width=False, height=False)
        self.overrideredirect(True)
        self.lift()

        self.SizeFont = int(ConfigResolution(self.MainAppli.Nconfig, 'MA'))

        self.ImgBtnClose, wsize, hsize, self.CanvasBtnClose, self.ImgCanvasBtnClose = CanInWindow(
            'Media/FrmAcqui/BtnClose/', self.RatioX, self.RatioY2, self.CanvasFrmFond,
            int(self.SX * 0.988), int(self.SY * 0.014), 0)
        ChangeCursor(self.CanvasBtnClose)
        self.CanvasBtnClose.bind('<Motion>',
                                 lambda action: self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose,
                                                                               image=self.ImgBtnClose[1]))
        self.CanvasBtnClose.bind('<ButtonRelease-1>', self.CacheFrmAcquisition)

        self.CanvasFrmFond.create_text(int(self.SX * 0.005), int(self.SY * 0.015), anchor=tk.W, text='Mode acquisition',
                                       font=FontLabel(10))
        self.LegendPanneau = self.CanvasFrmFond.create_text(int(self.SX * 0.755), int(self.SY * 0.042), anchor=tk.W,
                                                            text="Acquisition - Entrées analogiques de l'Arduino",
                                                            font=FontLabel(10))
        self.CanvasFrmFond.addtag_withtag('LegendPanneau', self.LegendPanneau)

        self.Graph = Graph_Acqui_Canvas(self.CanvasFrmFond, int(self.SX * 0.377), int(self.SY * 0.52),
                                        int(self.SX * 0.748), int(self.SY * 0.92), self)

        self.ImgArduino, wsize, hsize, self.CanvasArduino, self.ImgCanvasArduino = CanInWindow(
            'Media/FrmAcqui/Acqui/', self.RatioX * 0.7, self.RatioY * 0.7, self.CanvasFrmFond,
            int(self.SX * 0.875), int(self.SY * 0.45), 0)

        self.ImgUSB, wsize, hsize, self.CanvasUSB, self.ImgCanvasUSB = CanInWindow(
            'Media/FrmAcqui/USB/', self.RatioX * 0.7, self.RatioY * 0.7, self.CanvasFrmFond,
            int(self.SX * 0.933), int(self.SY * 0.18), 0)
        ChangeCursor(self.CanvasUSB)
        self.CanvasUSB.bind('<Button-1>', self.ConnectUSB)

        self.PinA = []
        for i in range(6):
            self.PinA.append(CanInWindow(
                'Media/FrmAcqui/PinA/', self.RatioX * 0.7, self.RatioY * 0.7, self.CanvasFrmFond,
                int(self.SX * 0.833), int(self.SY * 0.5475 + i * self.SY * 0.0132), 6))

        self.CanvasFrmFond.create_text(int(self.SX * 0.76), int(self.SY * 0.68), anchor=tk.W,
                                       text="Durée", font=FontLabelTitre(self.SizeFont))
        self.CanvasFrmFond.create_text(int(self.SX * 0.77), int(self.SY * 0.72), anchor=tk.W,
                                       text=". Totale (s) : ", font=FontLabel2(self.SizeFont-1))
        self.LabelTotal = LabelInCanvas(self.CanvasFrmFond, '', '#F7F7F7', FontLabel(self.SizeFont),
                                        int(self.SX * 0.82), int(self.SY * 0.708))
        self.LabelTotal.Label.config(text='---')

        self.CanvasFrmFond.create_text(int(self.SX * 0.77), int(self.SY * 0.76), anchor=tk.W,
                                       text=". Période d'échantillonnage (ms) : ", font=FontLabel2(self.SizeFont-1))
        self.LabelPeriode = LabelInCanvas(self.CanvasFrmFond, '', '#F7F7F7', FontLabel(self.SizeFont),
                                          int(self.SX * 0.912), int(self.SY * 0.748))
        self.LabelPeriode.Label.config(text='---')

        self.CanvasFrmFond.create_text(int(self.SX * 0.76), int(self.SY * 0.81), anchor=tk.W,
                                       text="Déclenchement", font=FontLabelTitre(self.SizeFont))
        self.CanvasFrmFond.create_text(int(self.SX * 0.77), int(self.SY * 0.85), anchor=tk.W,
                                       text=". Source : ", font=FontLabel2(self.SizeFont-1))
        self.LabelSource = LabelInCanvas(self.CanvasFrmFond, 'Aucune', '#F7F7F7', FontLabel(self.SizeFont),
                                         int(self.SX * 0.82), int(self.SY * 0.838))
        self.CanvasFrmFond.create_text(int(self.SX * 0.77), int(self.SY * 0.89), anchor=tk.W,
                                       text=". Niveau (V) : ", font=FontLabel2(self.SizeFont-1))
        self.LabelNiveau = LabelInCanvas(self.CanvasFrmFond, '---', '#F7F7F7', FontLabel(self.SizeFont),
                                         int(self.SX * 0.823), int(self.SY * 0.878))
        self.CanvasFrmFond.create_text(int(self.SX * 0.88), int(self.SY * 0.85), anchor=tk.W,
                                       text=". Sens : ", font=FontLabel2(self.SizeFont-1))
        self.LabelSens = LabelInCanvas(self.CanvasFrmFond, '---', '#F7F7F7', FontLabel(self.SizeFont),
                                       int(self.SX * 0.914), int(self.SY * 0.838))
        self.CanvasFrmFond.create_text(int(self.SX * 0.88), int(self.SY * 0.89), anchor=tk.W,
                                       text=". Pré-trigger (%) : ", font=FontLabel2(self.SizeFont-1))
        self.LabelTrigg = LabelInCanvas(self.CanvasFrmFond, '---', '#F7F7F7', FontLabel(self.SizeFont),
                                        int(self.SX * 0.952), int(self.SY * 0.878))

        self.MenuOnglets = MenuOnglets(self.CanvasFrmFond, int(self.SX * 0.875), int(self.SY * 0.98), self.RatioX,
                                       self.RatioY, 0, 'Acquisition', 'Tableur', 'Paramètres', self.SizeFont+1)
        for i in range(3):
            def GestEvt(evt, j=i):
                return self.ClicOnMenu(evt, j)

            self.MenuOnglets.ListCanvasMenu[i].bind('<Button-1>', GestEvt)

        self.CanvasFrmFond.bind('<Motion>', self.MoveOnCanvas)
        self.CanvasFrmFond.bind('<Button-1>', self.ClicOnCanvas)
        self.CanvasFrmFond.pack()

    def ClicOnMenu(self, _, j):
        self.MenuOnglets.InitOnglets2()
        self.MenuOnglets.ListCanvasMenu[j].itemconfig(self.MenuOnglets.ListImgMenu[j],
                                                      image=self.MenuOnglets.ListMenu[j][2])
        self.MenuOnglets.MenuSelected[j] = True
        if j == 0:
            self.CanvasFrmFond.itemconfigure('LegendPanneau', text="Acquisition - Entrées analogiques de l'Arduino")
            if self.TableurAcqui is not None:
                self.TableurAcqui.destroy()
                self.TableurAcqui = None
            if self.ParaAcqui is not None:
                self.ParaAcqui.destroy()
                self.ParaAcqui = None
        elif j == 1:
            self.CanvasFrmFond.itemconfigure('LegendPanneau', text="Acquisition - Tableur")
            self.TableurAcqui = Tableur_Graph_Acqui(self.CanvasFrmFond, self.RatioX, self.RatioY, self)
            if self.ParaAcqui is not None:
                self.ParaAcqui.destroy()
                self.ParaAcqui = None
        elif j == 2:
            self.CanvasFrmFond.itemconfigure('LegendPanneau', text="Acquisition - Paramètres")
            self.ParaAcqui = Para_Graph_Acqui(self.CanvasFrmFond, self.RatioX, self.RatioY, self)
            if self.TableurAcqui is not None:
                self.TableurAcqui.destroy()
                self.TableurAcqui = None

    def ConnectUSB(self, _):
        if self.MainAppli.ArduinoPort != '':
            if not self.USBConnected and self.Televersement:
                self.CanvasUSB.itemconfig(self.ImgCanvasUSB, image=self.ImgUSB[1])
                try:
                    self.ConnectSerial = serial.Serial(self.MainAppli.ArduinoPort, baudrate=9600, timeout=1)
                except:
                    tkMB.showerror('Attention', "Un problème s'est produit à l'ouverture du port.\n"
                                                "Vérifiez que le port utilisé par la carte Arduino est bien "
                                   + self.MainAppli.ArduinoPort + ".")
                    self.lift()
                else:
                    self.AcquiEnCours = False
                    self.USBConnected = True
                    self.Data_Acqui = []
                    self.Data_Acqui_Trigg = []
                    for i in range(6):
                        self.Data_Acqui.append([])
                        self.Data_Acqui_Trigg.append([])
                    self.Data_Temps = []
                    self.Data_Temps_Trigg = []
                    self.TempsAcqui = 0
                    self.TempsAcquiTrigg = 0
                    self.AcquiEnCours = False
                    while self.TempsAcqui <= self.DureeTotalAcqui + self.DureeTrigg:
                        if keyboard.is_pressed("esc"):
                            break
                        self.ImportDonneeSerial()
                        self.AffichGraphDonnees()
                    self.CanvasUSB.itemconfig(self.ImgCanvasUSB, image=self.ImgUSB[0])
                    self.USBConnected = False
                    self.ConnectSerial.close()
            else:
                tkMB.showwarning('Attention', "Les paramètres de l'acquisition n'ont pas été configuré !")
                self.lift()
        else:
            tkMB.showwarning('Attention', "Le port série de l'Arduino n'est pas configuré !")
            self.lift()

    def ImportDonneeSerial(self):
        donnee = str(self.ConnectSerial.readline())
        if donnee != "b''":
            donnee = donnee[2:len(donnee) - 6]
            listdonnee = donnee.split(';')
            self.ListPinActif = []
            for i in range(6):
                if self.PinActif[i]:
                    self.ListPinActif.append(i)
            try:
                for i in range(len(listdonnee)):
                    float(listdonnee[i])
            except:
                pass
            else:
                if self.Declenchement > 0:
                    data = float(listdonnee[self.Source - 1])
                else:
                    data = 0
                if not self.AcquiEnCours:
                    if self.Declenchement == 0:
                        self.AcquiEnCours = True
                    elif (self.Declenchement == 1 and data >= self.ValSeuil) or \
                            (self.Declenchement == 2 and data <= self.ValSeuil):
                        if len(self.Data_Acqui_Trigg[self.ListPinActif[self.Source - 1]]) > 0:
                            if (self.Declenchement == 1 and
                                data > self.Data_Acqui_Trigg[self.ListPinActif[self.Source - 1]][-1]) \
                                    or (self.Declenchement == 2 and data <
                                        self.Data_Acqui_Trigg[self.ListPinActif[self.Source - 1]][-1]):
                                self.AcquiEnCours = True
                        for t in range(len(self.Data_Temps_Trigg)):
                            if self.Data_Temps_Trigg[t] >= self.TempsAcquiTrigg - self.DureeTrigg:
                                self.Data_Temps.append(self.TempsAcqui)
                                self.TempsAcqui = self.TempsAcqui + self.Dt
                                for i in range(len(self.ListPinActif)):
                                    self.Data_Acqui[self.ListPinActif[i]].append(
                                        self.Data_Acqui_Trigg[self.ListPinActif[i]][t])
                    else:
                        self.Data_Temps_Trigg.append(self.TempsAcquiTrigg)
                        for i in range(len(listdonnee)):
                            self.Data_Acqui_Trigg[self.ListPinActif[i]].append(float(listdonnee[i]))
                        self.TempsAcquiTrigg = self.TempsAcquiTrigg + self.Dt
                if self.AcquiEnCours:
                    self.Data_Temps.append(self.TempsAcqui)
                    for i in range(len(listdonnee)):
                        self.Data_Acqui[self.ListPinActif[i]].append(float(listdonnee[i]))
            if self.AcquiEnCours:
                self.TempsAcqui = self.TempsAcqui + self.Dt

    def AffichGraphDonnees(self):
        for i in range(len(self.ListPinActif)):
            self.Graph.ListCourbes[self.ListPinActif[i]].set_data(self.Data_Temps,
                                                                  self.Data_Acqui[self.ListPinActif[i]])
        self.Graph.graphfig.draw()

    def MoveOnCanvas(self, _):
        self.MainAppli.CanvasBtnQuit.itemconfig(self.MainAppli.ImgCanvasBtnQuit, image=self.MainAppli.ImgBtnQuit[0])
        self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose, image=self.ImgBtnClose[0])
        self.MenuOnglets.InitOnglets()

    def ClicOnCanvas(self, _):
        if self.TableurAcqui is not None:
            self.TableurAcqui.lift()
        if self.ParaAcqui is not None:
            self.ParaAcqui.lift()

    def ActionTeleverser(self):
        arduinoCommand = '"' + self.MainAppli.CheminArduinoProg + '/arduino" --upload ' + " --board arduino:avr:uno" + \
                         " --port " + self.MainAppli.ArduinoPort + " " + self.SketchINOAcqui
        try:
            self.ConnectSerial = serial.Serial(self.MainAppli.ArduinoPort, baudrate=9600, timeout=1)
            self.ConnectSerial.close()
        except:
            tkMB.showerror('Attention', "Un problème s'est produit à l'ouverture du port.\n"
                                        "Vérifiez que le port utilisé par la carte Arduino est bien "
                           + self.MainAppli.ArduinoPort + ".")
            self.lift()
            self.ParaAcqui.lift()
        else:
            subprocess.call(arduinoCommand, shell=True)
            self.Televersement = True
            time.sleep(8)

    def CacheFrmAcquisition(self, _):
        self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose, image=self.ImgBtnClose[0])
        self.MainAppli.CanvasEtagCircuits.itemconfig(self.MainAppli.ImgCanvasEtagCircuits,
                                                     image=self.MainAppli.ImgEtagCircuits[1])
        self.USBConnected = False
        self.destroy()
        self.MainAppli.ModeAcquisitionActif = False
        self.MainAppli.parent.lift()
        self.MainAppli.FrmLift()


class Graph_Acqui_Canvas(tk.Canvas):
    def __init__(self, conteneur, X, Y, W, H, Appli):
        tk.Canvas.__init__(self, conteneur, width=W, height=H, highlightthickness=0, bd=0)
        conteneur.create_window(X, Y, anchor=tk.CENTER, window=self)
        self.MainAppli = Appli
        self.ListCourbes = []

        mydpi = 96
        self.fig = Figure(figsize=(W / mydpi, H / mydpi), dpi=mydpi, facecolor='white')
        self.Graph = self.fig.add_subplot(111)
        self.Graph.patch.set_facecolor('white')
        self.Graph.tick_params(axis="y", labelrotation=90)
        self.Graph.grid(which='major', alpha=0.5, linewidth=0.6, color="#ababab")

        self.graphfig = FigureCanvasTkAgg(self.fig, master=self)
        self.CanvasGraph = self.graphfig.get_tk_widget()
        self.CanvasGraph.bind('<Motion>', self.MoveOnCanvas)

        self.fig.tight_layout(rect=[0.01, 0.01, 0.98, 1])

        self.A0, = self.Graph.plot([], [], color='blue')
        self.A1, = self.Graph.plot([], [], color='green')
        self.A2, = self.Graph.plot([], [], color='orange')
        self.A3, = self.Graph.plot([], [], color='yellow')
        self.A4, = self.Graph.plot([], [], color='purple')
        self.A5, = self.Graph.plot([], [], color='brown')
        self.ListCourbes.append(self.A0)
        self.ListCourbes.append(self.A1)
        self.ListCourbes.append(self.A2)
        self.ListCourbes.append(self.A3)
        self.ListCourbes.append(self.A4)
        self.ListCourbes.append(self.A5)
        self.Graph.set_xlabel("Temps (s)", weight='bold')
        self.Graph.set_ylabel("", weight='bold')
        self.Graph.set_xlim(0, 10)
        self.Graph.set_ylim(0, 5.2)

        self.CanvasGraph.pack()
        self.graphfig.draw()

    def MoveOnCanvas(self, _):
        self.MainAppli.MenuOnglets.InitOnglets()


class Tableur_Graph_Acqui(tk.Toplevel):
    def __init__(self, container, RatioX, RatioY, Appli):
        tk.Toplevel.__init__(self, container)
        self.MainAppli = Appli
        self.RatioX = RatioX
        self.RatioY = RatioY
        self.DataList = []
        self.FileCSV = None

        screen = ctypes.windll.user32
        FrmFond = Image.open('Media/FrmAcqui/PanneauTab/01.bmp')
        self.SX = int((float(FrmFond.size[0]) * float(RatioX)))
        self.SY = int((float(FrmFond.size[1]) * float(RatioY)))

        self.ImgFrmFond = []
        self.ImgFrmFond = RedimImg(self.SX, self.SY, 'Media/FrmAcqui/PanneauTab/')
        self.CanvasFrmFond = CanvasApp(self, width=self.SX, height=self.SY)
        self.ImgCanvasFrmFond = self.CanvasFrmFond.create_image(0, 0, anchor=tk.NW, image=self.ImgFrmFond[0])

        self.geometry(str(self.SX) + "x" + str(self.SY) + "+" + str(int(screen.GetSystemMetrics(0) * 0.7525)) + "+" +
                      str(int(screen.GetSystemMetrics(1) * 0.085)))
        self.resizable(width=False, height=False)
        self.overrideredirect(True)

        self.FrameTableur = tk.Frame(self.CanvasFrmFond)
        self.CanvasFrmFond.create_window(int(self.SX * 0.5), int(self.SY * 0.52), anchor=tk.CENTER,
                                         window=self.FrameTableur)
        self.scrollable_canvas = ScrollableCanvas(self.FrameTableur, int(self.SX * 0.95),
                                                  int(self.SY * 0.935))
        self.scrollable_canvas.grid(row=1, column=1)

        tk.Label(self.scrollable_canvas.interior, text='', relief=tk.FLAT, width=int(self.SX * 0.01), bg='white',
                 font=FontLabel2(10), height=2).grid(row=0, column=0)

        self.TabLabelN = []
        self.TabLabelNCol = []
        self.TabLabels = []

        if len(self.MainAppli.ListPinActif) > 0:
            for r in range(len(self.MainAppli.Data_Acqui[self.MainAppli.ListPinActif[0]])):
                self.TabLabelN.append(tk.Label(self.scrollable_canvas.interior, text=str(r + 1), relief=tk.RIDGE,
                                               width=int(self.SX * 0.01), bg='white', font=FontLabel2(10)))
                self.TabLabelN[r].grid(row=r + 1, column=0)

                self.TabLabelCol = []
                for i in range(len(self.MainAppli.ListPinActif) + 1):
                    self.TabLabelNCol.append(
                        tk.Label(self.scrollable_canvas.interior, text='', relief=tk.RIDGE,
                                 width=int(self.SX * 0.02), height=2, bg='white', font=FontLabel2(11)))
                    self.TabLabelNCol[i].grid(row=0, column=i + 1)
                    self.TabLabelCol.append(tk.Label(self.scrollable_canvas.interior, text='', relief=tk.RIDGE,
                                                     width=int(self.SX * 0.02), bg='white', font=FontLabel(11)))
                    self.TabLabelCol[i].grid(row=r + 1, column=i + 1)
                    if i == 0:
                        self.TabLabelNCol[i]['text'] = 't (s)'
                    else:
                        self.TabLabelNCol[i]['text'] = 'A' + str(self.MainAppli.ListPinActif[i - 1]) + ' (V)'
                self.TabLabels.append(self.TabLabelCol)

            for r in range(len(self.MainAppli.Data_Acqui[self.MainAppli.ListPinActif[0]])):
                for c in range(len(self.MainAppli.ListPinActif) + 1):
                    if c > 0:
                        self.TabLabels[r][c]['text'] = str(
                            self.MainAppli.Data_Acqui[self.MainAppli.ListPinActif[c - 1]][r])
                    else:
                        self.TabLabels[r][c]['text'] = str(round(self.MainAppli.Data_Temps[r], 2))

        self.BtnCSV = BtnAction(self.CanvasFrmFond, int(self.SX * 0.15),
                                int(self.SY * 0.019), RatioX, RatioY, 'Media/FrmAcqui/BtnCSV/')
        self.BtnCSV.CanvasBtn.bind('<ButtonRelease-1>', self.Exporter)

        self.BtnExploit = BtnAction(self.CanvasFrmFond, int(self.SX * 0.06),
                                    int(self.SY * 0.019), RatioX, RatioY, 'Media/FrmAcqui/BtnGraph/')
        self.BtnExploit.CanvasBtn.bind('<ButtonRelease-1>', self.Exploiter)

        self.lift()
        self.CanvasFrmFond.bind('<Motion>', self.MoveOnCanvas)
        self.scrollable_canvas.canvas.bind('<Motion>', self.MoveOnCanvas)
        self.CanvasFrmFond.pack()

    def Exploiter(self, _):
        self.BtnExploit.CanvasBtn.itemconfig(self.BtnExploit.ImgCanvasBtn, image=self.BtnExploit.ImgBtn[0])
        if len(self.MainAppli.ListPinActif) > 0:
            self.DataList = []
            for r in range(len(self.MainAppli.Data_Acqui[self.MainAppli.ListPinActif[0]])):
                self.DataList.append(self.TabLabels[r][0]['text'])
                for c in range(len(self.MainAppli.ListPinActif)):
                    self.DataList[r] = self.DataList[r] + ';' + self.TabLabels[r][c + 1]['text']

            self.MainAppli.MainAppli.AffichTab = True
            self.lower()
            self.MainAppli.lower()
            self.MainAppli.MainAppli.FrmINO = FrmSketchIDE(
                self.MainAppli.MainAppli.parent, self.MainAppli.MainAppli.RatioFondX,
                self.MainAppli.MainAppli.RatioFondY,
                self.MainAppli.MainAppli.RatioFondY2, -1, self.MainAppli.MainAppli)
            self.MainAppli.MainAppli.FrmINO.ChargeSerialMoniteur()
            self.MainAppli.MainAppli.FrmINO.FrmSerialMonitor.ChargeTableur()
            self.MainAppli.MainAppli.FrmINO.FrmSerialMonitor.lower()
            self.MainAppli.MainAppli.FrmINO.FrmSerialMonitor.FrmTableur.lift()
            self.MainAppli.MainAppli.FrmINO.FrmSerialMonitor.FrmTableur.Tableur.AjoutDatas(self.DataList)
            for i in range(len(self.MainAppli.ListPinActif) + 1):
                self.MainAppli.MainAppli.FrmINO.FrmSerialMonitor.FrmTableur.Tableur.TabLabelNCol[i]['text'] = \
                    self.TabLabelNCol[i]['text']
                self.MainAppli.MainAppli.FrmINO.FrmSerialMonitor.FrmTableur.Tableur.TabExpressCol[i] = ''

    def Exporter(self, _):
        self.BtnCSV.CanvasBtn.itemconfig(self.BtnCSV.ImgCanvasBtn, image=self.BtnCSV.ImgBtn[0])
        if len(self.MainAppli.ListPinActif) > 0:
            self.FileCSV = tkfiledialog.asksaveasfilename(
                title="Enregistrer sous", filetypes=[('CSV files', '.csv')], initialdir="Sketchs/Saves/Exploit",
                defaultextension='.csv')
            if self.FileCSV != '':
                csvfile = open(self.FileCSV, 'w', newline='')
                SaveWriter = csv.writer(csvfile, delimiter=';')
                ValC = []
                ValExpress = []
                for j in range(len(self.MainAppli.ListPinActif) + 1):
                    ValC.append(self.TabLabelNCol[j]['text'])
                    ValExpress.append('')
                SaveWriter.writerow(ValC)
                SaveWriter.writerow(ValExpress)
                for i in range(len(self.MainAppli.Data_Acqui[self.MainAppli.ListPinActif[0]])):
                    ValC = []
                    for j in range(len(self.MainAppli.ListPinActif) + 1):
                        ValC.append(self.TabLabels[i][j]['text'])
                    SaveWriter.writerow(ValC)
                csvfile.close()
            self.MainAppli.lift()
            self.lift()

    def MoveOnCanvas(self, _):
        self.MainAppli.MenuOnglets.InitOnglets()


class Para_Graph_Acqui(tk.Toplevel):
    def __init__(self, container, RatioX, RatioY, Appli):
        tk.Toplevel.__init__(self, container)
        self.MainAppli = Appli
        self.RatioX = RatioX
        self.RatioY = RatioY
        self.ListSource = []
        self.Declenchement = False

        screen = ctypes.windll.user32
        FrmFond = Image.open('Media/FrmAcqui/Panneau/01.bmp')
        self.SX = int((float(FrmFond.size[0]) * float(RatioX)))
        self.SY = int((float(FrmFond.size[1]) * float(RatioY)))

        self.ImgFrmFond = []
        self.ImgFrmFond = RedimImg(self.SX, self.SY, 'Media/FrmAcqui/Panneau/')
        self.CanvasFrmFond = CanvasApp(self, width=self.SX, height=self.SY)
        self.ImgCanvasFrmFond = self.CanvasFrmFond.create_image(0, 0, anchor=tk.NW, image=self.ImgFrmFond[0])

        self.geometry(str(self.SX) + "x" + str(self.SY) + "+" + str(int(screen.GetSystemMetrics(0) * 0.753)) + "+" +
                      str(int(screen.GetSystemMetrics(1) * 0.10)))
        self.resizable(width=False, height=False)
        self.overrideredirect(True)

        self.ImgArduino, wsize, hsize, self.CanvasArduino, self.ImgCanvasArduino = CanInWindow(
            'Media/FrmAcqui/Acqui/', self.RatioX * 0.7, self.RatioY * 0.7, self.CanvasFrmFond,
            int(self.SX * 0.5), int(self.SY * 0.22), 0)

        self.PinA = []
        self.PinActif = [False, False, False, False, False, False]
        for i in range(6):
            self.PinA.append(CanInWindow(
                'Media/FrmAcqui/PinA/', self.RatioX * 0.7, self.RatioY * 0.7, self.CanvasFrmFond,
                int(self.SX * 0.328), int(self.SY * 0.331 + i * self.SY * 0.014), 6))

            def GestEvt(evt, j=i):
                return self.ClicOnPin(evt, j)

            self.PinA[i][3].bind('<Button-1>', GestEvt)
            ChangeCursor(self.PinA[i][3])

        for i in range(6):
            self.PinActif[i] = self.MainAppli.PinActif[i]
            if self.PinActif[i]:
                self.PinA[i][3].itemconfig(self.PinA[i][4], image=self.PinA[i][0][i])
            else:
                self.PinA[i][3].itemconfig(self.PinA[i][4], image=self.PinA[i][0][6])

        self.CanvasFrmFond.create_text(int(self.SX * 0.05), int(self.SY * 0.50), anchor=tk.W,
                                       text="Acquisition - Entrées analogiques",
                                       font=FontLabelTitre(self.MainAppli.SizeFont))
        self.LabelAnalogInput = LabelInCanvas(self.CanvasFrmFond, '', '#F7F7F7', FontLabel(self.MainAppli.SizeFont),
                                              int(self.SX * 0.1), int(self.SY * 0.54))

        self.CanvasFrmFond.create_text(int(self.SX * 0.05), int(self.SY * 0.62), anchor=tk.W,
                                       text="Durée", font=FontLabelTitre(self.MainAppli.SizeFont))
        self.CanvasFrmFond.create_text(int(self.SX * 0.07), int(self.SY * 0.67), anchor=tk.W,
                                       text=". Totale (s) : ", font=FontLabel2(self.MainAppli.SizeFont-1))
        self.Total = tk.StringVar()
        self.Total.set(str(self.MainAppli.DureeTotalAcqui))
        self.EntryTotal = tk.Entry(self.CanvasFrmFond, width=int(self.SX * 0.02), font=FontLabel(10),
                                   textvariable=self.Total, justify='right')
        self.CanvasFrmFond.create_window(int(self.SX * 0.3), int(self.SY * 0.67), anchor=tk.W, window=self.EntryTotal)
        self.EntryTotal.bind('<Return>', self.EnterTotal)

        self.CanvasFrmFond.create_text(int(self.SX * 0.07), int(self.SY * 0.72), anchor=tk.W,
                                       text=". Période d'échantillonnage (ms) : ",
                                       font=FontLabel2(self.MainAppli.SizeFont-1))
        self.Periode = tk.StringVar()
        self.Periode.set(str(self.MainAppli.Dt * 1000))
        self.EntryPeriode = tk.Entry(self.CanvasFrmFond, width=int(self.SX * 0.02), font=FontLabel(10),
                                     textvariable=self.Periode, justify='right')
        self.CanvasFrmFond.create_window(int(self.SX * 0.66), int(self.SY * 0.72), anchor=tk.W,
                                         window=self.EntryPeriode)
        self.EntryPeriode.bind('<Return>', self.EnterPeriode)

        self.CanvasFrmFond.create_text(int(self.SX * 0.05), int(self.SY * 0.79), anchor=tk.W,
                                       text="Déclenchement", font=FontLabelTitre(self.MainAppli.SizeFont))
        self.CanvasFrmFond.create_text(int(self.SX * 0.07), int(self.SY * 0.84), anchor=tk.W,
                                       text=". Source : ", font=FontLabel2(self.MainAppli.SizeFont-1))

        self.ListeSource = ListeDeroulante(self.CanvasFrmFond, int(self.SX * 0.02), values=self.ListSource)
        self.CanvasFrmFond.create_window(int(self.SX * 0.3), int(self.SY * 0.84), anchor=tk.W, window=self.ListeSource)
        self.ListeSource.bind("<<ComboboxSelected>>", self.SelectSource)

        self.CanvasFrmFond.create_text(int(self.SX * 0.07), int(self.SY * 0.89), anchor=tk.W,
                                       text=". Niveau (V) : ", font=FontLabel2(self.MainAppli.SizeFont-1))
        self.Niveau = tk.StringVar()
        self.Niveau.set(str(self.MainAppli.ValSeuil))
        self.EntryNiveau = tk.Entry(self.CanvasFrmFond, width=int(self.SX * 0.02), font=FontLabel(10),
                                    textvariable=self.Niveau, justify='right')
        self.CanvasFrmFond.create_window(int(self.SX * 0.3), int(self.SY * 0.89), anchor=tk.W, window=self.EntryNiveau)
        self.EntryNiveau.bind('<Return>', self.EnterNiveau)

        self.CanvasFrmFond.create_text(int(self.SX * 0.55), int(self.SY * 0.84), anchor=tk.W,
                                       text=". Sens : ", font=FontLabel2(self.MainAppli.SizeFont-1))
        self.ListSens = ['Montant', 'Descendant']
        self.ListeSens = ListeDeroulante(self.CanvasFrmFond, int(self.SX * 0.028), values=self.ListSens)
        self.CanvasFrmFond.create_window(int(self.SX * 0.75), int(self.SY * 0.84), anchor=tk.W, window=self.ListeSens)

        self.CanvasFrmFond.create_text(int(self.SX * 0.55), int(self.SY * 0.89), anchor=tk.W,
                                       text=". Pré-trigger (%) : ", font=FontLabel2(self.MainAppli.SizeFont-1))
        self.Trigger = tk.StringVar()
        self.Trigger.set('0')
        self.EntryTrigger = tk.Entry(self.CanvasFrmFond, width=int(self.SX * 0.015), font=FontLabel(10),
                                     textvariable=self.Trigger, justify='right')
        self.CanvasFrmFond.create_window(int(self.SX * 0.85), int(self.SY * 0.89), anchor=tk.W,
                                         window=self.EntryTrigger)
        self.EntryTrigger.bind('<Return>', self.EnterTrigg)

        if self.MainAppli.Declenchement > 0:
            self.ListeSens.current(self.MainAppli.Declenchement - 1)
            self.Declenchement = True
        else:
            self.ListeSens.config(state='disabled')
            self.EntryNiveau.config(state='disabled')
            self.EntryTrigger.config(state='disabled')

        self.MAJAnalogInput()
        self.ListeSource.current(self.MainAppli.Source)

        self.BtnAppliquer = tk.Button(self.CanvasFrmFond, text='Appliquer', command=self.Appliquer)
        self.CanvasFrmFond.create_window(int(self.SX * 0.8), int(self.SY * 0.96),
                                         anchor=tk.CENTER, window=self.BtnAppliquer)
        self.BtnAppliquer.bind('<Return>', self.ActionAppliquer)

        self.lift()
        self.CanvasFrmFond.bind('<Motion>', self.MoveOnCanvas)
        self.CanvasFrmFond.pack()

    def ClicOnPin(self, _, j):
        if not self.PinActif[j]:
            self.PinA[j][3].itemconfig(self.PinA[j][4], image=self.PinA[j][0][j])
            self.PinActif[j] = True
        else:
            self.PinA[j][3].itemconfig(self.PinA[j][4], image=self.PinA[j][0][6])
            self.PinActif[j] = False
        self.MAJAnalogInput()

    def MAJAnalogInput(self):
        TextAnalogInput = ''
        self.ListSource = []
        self.ListSource.append('Aucune')
        for i in range(6):
            if self.PinActif[i]:
                if TextAnalogInput != "":
                    TextAnalogInput = TextAnalogInput + " - A" + str(i)
                else:
                    TextAnalogInput = "A" + str(i)
                self.ListSource.append("A" + str(i))
        self.ListeSource.config(values=self.ListSource)
        if len(self.ListSource) == 1:
            self.ListeSource.current(0)
            self.ListeSens.config(state='disabled')
            self.EntryNiveau.config(state='disabled')
            self.EntryTrigger.config(state='disabled')
            self.ListeSens.set('')
            self.Declenchement = False
        elif self.Declenchement:
            self.ListeSource.current(1)
        self.LabelAnalogInput.Label.config(text=TextAnalogInput)

    def SelectSource(self, _):
        if self.ListeSource.current() != 0:
            self.ListeSens.config(state='readonly')
            self.EntryNiveau.config(state='normal')
            self.EntryTrigger.config(state='normal')
            self.ListeSens.current(0)
        else:
            self.ListeSens.config(state='disabled')
            self.EntryNiveau.config(state='disabled')
            self.EntryTrigger.config(state='disabled')
            self.ListeSens.set('')

    def ActionAppliquer(self, _):
        self.Appliquer()

    def Appliquer(self):
        self.MainAppli.Televersement = False
        if self.MainAppli.MainAppli.ArduinoPort != '':
            self.ActionEnterTotal()
            if self.Total.get() != '':
                self.MainAppli.LabelTotal.Label.config(text=self.Total.get())
                self.MainAppli.DureeTotalAcqui = float(self.Total.get())
            else:
                return
            self.ActionEnterPeriode()
            if self.Periode.get() != '':
                self.MainAppli.LabelPeriode.Label.config(text=self.Periode.get())
                self.MainAppli.Dt = float(self.Periode.get()) / 1000
            else:
                return
            self.MainAppli.LabelSource.Label.config(text=self.ListeSource.get())
            self.MainAppli.Source = self.ListeSource.current()
            self.MainAppli.Declenchement = self.ListeSens.current() + 1
            self.MainAppli.LabelSens.Label.config(text=self.ListeSens.get())

            if self.MainAppli.Declenchement > 0:
                self.ActionEnterNiveau()
                if self.Niveau.get() != '':
                    self.MainAppli.ValSeuil = float(self.Niveau.get())
                    self.MainAppli.LabelNiveau.Label.config(text=self.Niveau.get())
                else:
                    return
                self.ActionEnterTrigg()
                if self.Trigger.get() != '':
                    self.MainAppli.LabelTrigg.Label.config(text=self.Trigger.get())
                    if self.Total.get() != '':
                        self.MainAppli.DureeTrigg = float(self.Total.get()) * float(self.Trigger.get()) / 100
                else:
                    return

            for i in range(6):
                self.MainAppli.PinActif[i] = self.PinActif[i]
                if self.PinActif[i]:
                    self.MainAppli.PinA[i][3].itemconfig(self.MainAppli.PinA[i][4], image=self.MainAppli.PinA[i][0][i])
                else:
                    self.MainAppli.PinA[i][3].itemconfig(self.MainAppli.PinA[i][4], image=self.MainAppli.PinA[i][0][6])

            for i in range(6):
                self.MainAppli.Graph.ListCourbes[i].set_data([], [])
            self.MainAppli.Graph.Graph.set_ylabel(self.LabelAnalogInput.Label.cget("text") + " (V)")
            self.MainAppli.Graph.Graph.set_xlim(0, self.MainAppli.DureeTotalAcqui + self.MainAppli.DureeTrigg)
            self.MainAppli.Graph.graphfig.draw()

            self.SaveParametres()

            if self.MainAppli.Televersement:
                self.destroy()
                self.MainAppli.MainAppli.parent.lift()
                self.MainAppli.lift()
                self.MainAppli.CanvasFrmFond.itemconfigure('LegendPanneau',
                                                           text="Acquisition - Entrées analogiques de l'Arduino")
                self.MainAppli.MenuOnglets.ListCanvasMenu[0].itemconfig(self.MainAppli.MenuOnglets.ListImgMenu[0],
                                                                        image=self.MainAppli.MenuOnglets.ListMenu[0][2])
                self.MainAppli.MenuOnglets.MenuSelected[0] = True
                self.MainAppli.MenuOnglets.ListCanvasMenu[2].itemconfig(self.MainAppli.MenuOnglets.ListImgMenu[2],
                                                                        image=self.MainAppli.MenuOnglets.ListMenu[2][0])
                self.MainAppli.MenuOnglets.MenuSelected[2] = False
                self.MainAppli.lift()
        else:
            tkMB.showwarning('Attention', "Le port série de l'Arduino n'est pas configuré !")
            self.MainAppli.lift()
            self.lift()

    def SaveParametres(self):
        FileInoToSave = open(self.MainAppli.SketchINOAcqui, "w", encoding="utf-8", )
        InoToSave = 'void setup() {\nSerial.begin(9600);}\n\nvoid loop() {\n'

        for i in range(6):
            if self.PinActif[i]:
                InoToSave = InoToSave + "Serial.print(analogRead(A" + str(i) + ")*5.00/1023);\nSerial.print(';');\n"

        InoToSave = InoToSave + 'Serial.println();\ndelay(' + self.Periode.get() + ');}'
        FileInoToSave.write(InoToSave)
        FileInoToSave.close()
        self.MainAppli.ActionTeleverser()

    def MoveOnCanvas(self, _):
        self.MainAppli.MenuOnglets.InitOnglets()

    def EnterTotal(self, _):
        self.ActionEnterTotal()

    def ActionEnterTotal(self):
        try:
            Total = float(self.Total.get())
        except:
            tkMB.showwarning('Attention', "La valeur de la durée d'acquisition n'est pas valide!")
            self.MainAppli.lift()
            self.lift()
            self.Total.set('')
            self.EntryTotal.focus_set()
        else:
            if Total >= 0.1:
                self.BtnAppliquer.focus_set()
            else:
                tkMB.showwarning('Attention', "La durée d'acquisition doit être supérieure ou égale à 100 ms!")
                self.MainAppli.lift()
                self.lift()
                self.Total.set('')
                self.EntryTotal.focus_set()

    def EnterPeriode(self, _):
        self.ActionEnterPeriode()

    def ActionEnterPeriode(self):
        try:
            Periode = float(self.Periode.get())
        except:
            tkMB.showwarning('Attention', "La valeur de la période d'échantillonnage n'est pas valide!")
            self.MainAppli.lift()
            self.lift()
            self.Periode.set('')
            self.EntryPeriode.focus_set()
        else:
            if Periode >= 0.1:
                self.BtnAppliquer.focus_set()
            else:
                tkMB.showwarning('Attention', "La période d'échantillonnage doit être supérieure ou égale à 100 ms!")
                self.MainAppli.lift()
                self.lift()
                self.Periode.set('')
                self.EntryPeriode.focus_set()

    def EnterNiveau(self, _):
        self.ActionEnterNiveau()

    def ActionEnterNiveau(self):
        try:
            Niveau = float(self.Niveau.get())
        except:
            tkMB.showwarning('Attention', "La valeur du niveau de déclenchement n'est pas valide!")
            self.MainAppli.lift()
            self.lift()
            self.Niveau.set('')
            self.EntryNiveau.focus_set()
        else:
            if 0 < Niveau < 5:
                self.BtnAppliquer.focus_set()
            else:
                tkMB.showwarning('Attention', "Le niveau de déclenchement doit être compris entre 0 et 5 V !")
                self.MainAppli.lift()
                self.lift()
                self.Niveau.set('')
                self.EntryNiveau.focus_set()

    def EnterTrigg(self, _):
        self.ActionEnterTrigg()

    def ActionEnterTrigg(self):
        try:
            Trigg = float(self.Trigger.get())
        except:
            tkMB.showwarning('Attention', "La valeur de pré-trigger n'est pas valide!")
            self.MainAppli.lift()
            self.lift()
            self.Trigger.set('')
            self.EntryTrigger.focus_set()
        else:
            if 0 <= Trigg <= 100:
                self.BtnAppliquer.focus_set()
            else:
                tkMB.showwarning('Attention', "Le pré-trigger doit être compris entre 0 et 100 % !")
                self.MainAppli.lift()
                self.lift()
                self.Trigger.set('')
                self.EntryTrigger.focus_set()
