from AppliDef import *
from Tableur import *
import serial


class FrmSerialMonitor(tk.Toplevel):
    def __init__(self, container, SX, SY, Appli):
        tk.Toplevel.__init__(self, container)

        screen = ctypes.windll.user32
        self.FrmSerialMonitorSX = SX
        self.FrmSerialMonitorSY = SY
        self.MainAppli = Appli
        self.USBConnect = False
        self.SerialThreadStart = False
        self.ConnectSerial = None
        self.SerialThread = None
        self.MainAppli.MainAppli.SerialMonitor = True
        self.FrmTableur = None
        self.AffichTab = False

        self.geometry(str(self.FrmSerialMonitorSX) + "x" + str(self.FrmSerialMonitorSY) + "+" +
                      str(int(screen.GetSystemMetrics(0) * 0.174)) + "+" +
                      str(int(screen.GetSystemMetrics(1) * 0.080)))
        self.resizable(width=False, height=False)
        self.overrideredirect(True)

        self.ImgFond = Image.open('Media/FrmSerialMonitor/Fond/Fond.jpg')
        self.RatioImgx = float(self.FrmSerialMonitorSX) / float(self.ImgFond.size[0])
        self.RatioImgy = float(self.FrmSerialMonitorSY) / float(self.ImgFond.size[1])

        self.ImgFrmSerialMonitor = RedimImg(self.FrmSerialMonitorSX, self.FrmSerialMonitorSY,
                                            'Media/FrmSerialMonitor/Fond/')
        self.CanvasFrmSerialMonitor = CanvasApp(self, width=self.FrmSerialMonitorSX, height=self.FrmSerialMonitorSY)
        self.ImgCanvasFrmSerialMonitor = self.CanvasFrmSerialMonitor.create_image(0, 0, anchor=tk.NW,
                                                                                  image=self.ImgFrmSerialMonitor[0])

        self.ImgBtnClose, wsize, hsize, self.CanvasBtnClose, self.ImgCanvasBtnClose = CanInWindow(
            'Media/FrmSerialMonitor/BtnClose/', self.RatioImgx, self.RatioImgy, self.CanvasFrmSerialMonitor,
            int(self.FrmSerialMonitorSX * 0.975), int(self.FrmSerialMonitorSY * 0.018), 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.CacheFrmSerialMonitor)

        self.CanvasFrmSerialMonitor.bind('<Motion>',
                                         lambda action: self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose,
                                                                                       image=self.ImgBtnClose[0]))

        ZDTWidth = int(self.FrmSerialMonitorSX * float(ConfigResolution(self.MainAppli.MainAppli.Nconfig, 'SM1')))

        ZDTHeight = int(self.FrmSerialMonitorSX * float(ConfigResolution(self.MainAppli.MainAppli.Nconfig, 'SM2')))

        self.ZoneTextSM = ZoneScrolledText(self.CanvasFrmSerialMonitor, width=ZDTWidth, height=ZDTHeight,
                                           font=FontText2(12))
        self.CanvasFrmSerialMonitor.create_window(int(self.FrmSerialMonitorSX * 0.004),
                                                  int(self.FrmSerialMonitorSY * 0.069), anchor=tk.NW,
                                                  window=self.ZoneTextSM)

        self.ImgBtnUSB, wsize, hsize, self.CanvasBtnUSB, self.ImgCanvasBtnUSB = CanInWindow(
            'Media/FrmSerialMonitor/USB/', self.RatioImgx, self.RatioImgy, self.CanvasFrmSerialMonitor,
            int(self.FrmSerialMonitorSX * 0.05), int(self.FrmSerialMonitorSY * 0.98), 0)
        ChangeCursor(self.CanvasBtnUSB)
        self.CanvasBtnUSB.bind('<Button-1>', self.ActionConnectUSB)

        ZDEWidth = int(self.FrmSerialMonitorSX * float(ConfigResolution(self.MainAppli.MainAppli.Nconfig, 'SM3')))
        SizeFont = int(ConfigResolution(self.MainAppli.MainAppli.Nconfig, 'SM4'))
        FontEntrySM = FontText2(SizeFont)

        self.EntrySM = tk.Entry(self.CanvasFrmSerialMonitor, width=ZDEWidth, font=FontEntrySM)
        self.CanvasFrmSerialMonitor.create_window(int(self.FrmSerialMonitorSX * 0.005),
                                                  int(self.FrmSerialMonitorSY * 0.039), anchor=tk.NW,
                                                  window=self.EntrySM)

        self.EntrySM.bind('<Motion>', lambda action: self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose,
                                                                                    image=self.ImgBtnClose[0]))
        self.EntrySM.bind('<Return>', self.SendSerial)

        self.ImgBtnSend, wsize, hsize, self.CanvasBtnSend, self.ImgCanvasBtnSend = CanInWindow(
            'Media/FrmSerialMonitor/BtnSend/', self.RatioImgx, self.RatioImgy, self.CanvasFrmSerialMonitor,
            int(self.FrmSerialMonitorSX * 0.963), int(self.FrmSerialMonitorSY * 0.049), 0)
        ChangeCursor(self.CanvasBtnSend)
        self.CanvasBtnSend.bind('<ButtonPress-1>', lambda action: self.CanvasBtnSend.itemconfig(self.ImgCanvasBtnSend,
                                                                                                image=self.ImgBtnSend[
                                                                                                    1]))
        self.CanvasBtnSend.bind('<ButtonRelease-1>', self.SendSerial)
        self.CanvasBtnSend.bind('<Motion>', lambda action: self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose,
                                                                                          image=self.ImgBtnClose[0]))

        self.BtnSupp = BtnAction(self.CanvasFrmSerialMonitor, int(self.FrmSerialMonitorSX * 0.89),
                                 int(self.FrmSerialMonitorSY * 0.981), self.RatioImgx,
                                 self.RatioImgy, 'Media/FrmSerialMonitor/BtnSupp/')
        self.BtnSupp.CanvasBtn.bind('<ButtonRelease-1>', self.EffaceDatas)

        self.varchoix = tk.IntVar()
        self.CaseDefilAuto = CaseACocher(self.CanvasFrmSerialMonitor, 'Défilement automatique', font=FontLabel(10),
                                         variable=self.varchoix, bg='#F7F7F7')
        self.CanvasFrmSerialMonitor.create_window(int(self.FrmSerialMonitorSX * 0.68),
                                                  int(self.FrmSerialMonitorSY * 0.981),
                                                  anchor=tk.W, window=self.CaseDefilAuto)
        self.varchoix.set(1)

        self.BtnTableur = BtnAction(self.CanvasFrmSerialMonitor, int(self.FrmSerialMonitorSX * 0.02),
                                    int(self.FrmSerialMonitorSY * 0.02), self.RatioImgx,
                                    self.RatioImgy, 'Media/FrmSerialMonitor/BtnTableur/')
        self.BtnTableur.CanvasBtn.bind('<ButtonRelease-1>', self.AffichTableur)

        self.CanvasFrmSerialMonitor.pack()

    def ActionConnectUSB(self, _):
        self.ConnectUSB()

    def ConnectUSB(self):
        if self.MainAppli.MainAppli.ArduinoPort != '':
            if not self.USBConnect:
                try:
                    self.ConnectSerial = serial.Serial(self.MainAppli.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.MainAppli.ArduinoPort + ".")
                    self.lift()
                else:
                    self.EntrySM.focus_set()
                    self.ZoneTextSM.delete(0.0, tk.END)
                    self.CanvasBtnUSB.itemconfig(self.ImgCanvasBtnUSB, image=self.ImgBtnUSB[1])
                    self.SerialThread = MyThread(self.ImportDonneeSerial)
                    self.SerialThread.start()
                    self.SerialThreadStart = True
                    self.USBConnect = True
            else:
                self.CanvasBtnUSB.itemconfig(self.ImgCanvasBtnUSB, image=self.ImgBtnUSB[0])
                self.SerialThread.stop()
                self.ConnectSerial.close()
                self.USBConnect = False
                self.focus_set()
        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) - 5]
            self.ZoneTextSM.insert(tk.INSERT, donnee + '\n')
            if self.varchoix.get() == 1:
                self.ZoneTextSM.see("end")

    def SendSerial(self, _):
        if self.USBConnect:
            self.CanvasBtnSend.itemconfig(self.ImgCanvasBtnSend, image=self.ImgBtnSend[0])
            self.ConnectSerial.write(self.EntrySM.get().encode('utf-8'))
            self.EntrySM.delete(0, 'end')

    def AffichTableur(self, _):
        if self.USBConnect:
            self.ConnectUSB()
        self.BtnTableur.CanvasBtn.itemconfig(self.BtnTableur.ImgCanvasBtn, image=self.BtnTableur.ImgBtn[0])
        self.MainAppli.MainAppli.AffichTabSM = True
        self.ChargeTableur()
        self.AffichTab = True

    def ChargeTableur(self):
        self.FrmTableur = FrmTableur(self.MainAppli.MainAppli.parent, self.RatioImgx, self.RatioImgy, self)
        self.MainAppli.MainAppli.AffichTab = True

    def EffaceDatas(self, _):
        self.BtnSupp.CanvasBtn.itemconfig(self.BtnSupp.ImgCanvasBtn, image=self.BtnSupp.ImgBtn[0])
        self.ZoneTextSM.delete(0.0, tk.END)

    def CacheFrmSerialMonitor(self, _):
        self.ActionCacheFrmSerialMonitor()

    def ActionCacheFrmSerialMonitor(self):
        if self.USBConnect:
            self.SerialThread.stop()
            self.ConnectSerial.close()
        self.destroy()
        self.MainAppli.MainAppli.parent.lift()
        self.MainAppli.MainAppli.SerialMonitor = False

        if not self.MainAppli.MainAppli.AffichSM:
            self.MainAppli.MainAppli.FrmINO.lift(self.MainAppli.MainAppli.parent)
        else:
            self.MainAppli.MainAppli.AffichSM = False
            self.MainAppli.MainAppli.FrmINO.destroy()
            self.MainAppli.MainAppli.FrmINO = None
            self.MainAppli.MainAppli.Init = False
            self.MainAppli.MainAppli.ActionAffichEtagSketch()
            self.MainAppli.MainAppli.Init = False
            self.MainAppli.MainAppli.MotionBtnV(0)

        if self.MainAppli.MainAppli.AffichCode:
            self.MainAppli.MainAppli.FrmCode.lift(self.MainAppli.MainAppli.parent)
        elif self.MainAppli.MainAppli.AffichDescript:
            self.MainAppli.MainAppli.FrmDescrip.lift(self.MainAppli.MainAppli.parent)
        elif self.MainAppli.MainAppli.AffichDoc:
            self.MainAppli.MainAppli.FrmDoc.lift(self.MainAppli.MainAppli.parent)

        self.MainAppli.MainAppli.CanvasEtagCircuits.itemconfig(
            self.MainAppli.MainAppli.ImgCanvasEtagCircuits, image=self.MainAppli.MainAppli.ImgEtagCircuits[1])
